举例如图,要算出苹果、梨子、西瓜中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
--各类水果的数量
举例如图,要算出苹果、梨子、西瓜中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
运行结果如图:
但感觉好复杂啊,各位大神有没有建议