您的位置:首页 > 数据库

SQL 百分比

2008-03-18 20:13 134 查看
问:

某个表数据如下:

A

A

A

B

B

B

B

C

C

D

有没有办法用sql写出一个语句,查询结果如下:

A 30%

B 40%

C 20%

D 10%

答:

--創建測試環境

Create Table test1

(

ftest Varchar(20))

Insert test1 Select 'A'

Union All Select 'A'

Union All Select 'A'

Union All Select 'B'

Union All Select 'B'

Union All Select 'B'

Union All Select 'B'

Union All Select 'C'

Union All Select 'C'

Union All Select 'D'

--查询

select ftest, 百分比=cast(cast(count(*)*100./(select count(*) from test1) as decimal(10,0)) as varchar)+'%'

from test1

group by ftest

go

--删除测试

drop table test1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: