SQL实现占比

表如下:
ID
NAME

1
a

2
a

1
a

1
a

2
a

希望实现效果:
ID 数量 占比
1 3 0.6
2 2 0.4
这个的SQL语句,十分感谢!
表是这个样子的

sqlserver写法

创建表

create table test
(id int,
name varchar(1))
insert into test values (1,'a')
insert into test values (2,'a')
insert into test values (1,'a')
insert into test values (1,'a')
insert into test values (2,'a')

执行

select a.id,a.count1,(a.count1+0.0)/b.count2
from
(select id,count(*) count1 from test group by id) a,
(select count(*) count2 from test) b

 

结果

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-12-18
declare @a table(id int,name varchar(20)) 
insert into @a values (1,'a') 
insert into @a values (2,'a') 
insert into @a values (1,'a') 
insert into @a values (1,'a') 
insert into @a values (2,'a')
select id,datacount=sum(1),sum(1)*1.0/b.sumcount as '占比'
from @a a
inner join (select sumcount=sum(1) from @a) b  on 1=1
group by id,b.sumcount

结果如下:

 

--上述语句在大数据情况下效率会高一些。

第2个回答  2013-12-18
select t.`id` as id ,(select SUM(t1.`id`) from table t1 where t1.`id` = t.`id`) as 数量,(select SUM(t1.`id`) from table t1 where t1.`id` = t.`id`)/(select COUNT(*) from table ) as 占比 from table as t GROUP BY t.`id`