举例如图,要算出苹果、梨子、西瓜中pz=1的数量占各自总数量的百分比,sql该如何写呢?本人菜鸟一只,求各路好汉帮忙,多谢!
我只写出了这个
select type,COUNT(pz) from biao
where pz=1
group by type
--各类水果pz=1的数量
select type,COUNT(pz) from biao
group by type
--各类水果的数量
楼主自己想了很久,只想到这个
select table1.t as 水果,table1.shu as 'pz=1的数量',table2.shu as 总数量,cast(table1.shu*100/table2.shu as varchar)+'%' as 'pz=1占比' from
(select type as t,COUNT(pz) as shu from ten where pz=1 group by type) as table1
left join (select type as t,COUNT(*) as shu from ten group by type) as table2 on table1.t=table2.t
运行结果如图:
但感觉好复杂啊,各位大神有没有建议
select type,sum(PZ) as 'PZ=1', count(pz) as '总数', sum(PZ)/count(PZ)*100 as ''占比 from Table group by Type
select type,sum(pz),count(type), sum(pz)*0.1/count(type)*10 from t group by type
少乘了个10
select type,sum(pz),count(type), sum(pz)*0.1/count(type) from t group by type
一句解决的事,搞得那么麻烦