我有一张表(简化),如此
ID1 ID2 Status
--- --- ------
1 33 0
1 33 0
1 33 1
1 33 1
1 34 1
1 34 2
2 33 0
2 33 0
2 34 0
我希望计算按状态类型分组的状态总数,以及与特定ID ID1& ID相关的状态数的百分比。 ID2
示例输出为
ID1 ID2 Status Count Percentage
--- --- ------ ----- ----------
1 33 0 2 50%
1 33 1 2 50%
1 34 1 1 50%
1 34 2 1 50%
2 33 0 2 100%
2 34 0 1 100%
到目前为止,我只能得到计数,但不是百分比。这是我现在的查询
select ID1, ID2 , status, count(ID2) as Count
from
StatTable
group by ID1, ID2, status
答案 0 :(得分:4)
您可以使用窗口函数获取百分比,以获得每个id1
,id2
组合的总数:
select ID1, ID2 , status, count(*) as cnt,
count(*) * 100.0 / count(*) over (partition by id1, id2) as Percentage
from StatTable
group by ID1, ID2, status;
答案 1 :(得分:0)
我对Gordon查询做了一些小改动,现在它与你预期的答案匹配 -
select ID1, ID2 , status, count(*) as cnt,
100.0 / count(*) over (partition by id1, id2) as Percentage
from table1TEmp
group by ID1, ID2, status;
答案 2 :(得分:0)
这对我有用
select ID1, ID2 , status, count(ID2) as cnt,
count(ID2) * 100.0 / (select count(ID2) from StatTable group by ID1) as Percentage
from StatTable
group by ID1, ID2, status;