Sql Postgres:组查询
我使用一些示例数据获得了以下表格模式:Sql Postgres:组查询,sql,postgresql,Sql,Postgresql,我使用一些示例数据获得了以下表格模式: country | month | code | code_count US 1 A1 2 US 1 A2 7 US 1 A3 3 US 2 B1 7 US 2 B2 9 US 2 B3 4 US 3 C1 3 US
country | month | code | code_count
US 1 A1 2
US 1 A2 7
US 1 A3 3
US 2 B1 7
US 2 B2 9
US 2 B3 4
US 3 C1 3
US 3 C2 6
US 3 C3 1
我需要一个查询,该查询将计算按国家和月份分组的百分比。我期望得到以下结果:
country | month | code | code_count | percentage
US 1 A1 2 16.7 -- 2 / (2 + 7 + 3)
US 1 A2 7 58.7 -- 7 / (2 + 7 + 3)
US 1 A3 3 25.0 -- 3 / (2 + 7 + 3)
US 2 B1 7 35.0 -- 7 / (7 + 9 + 4)
US 2 B2 9 45.0 -- 9 / (7 + 9 + 4)
US 2 B3 4 20.0 -- 4 / (7 + 9 + 4)
US 3 C1 3 30.0 -- 3 / (3 + 6 + 1)
US 3 C2 6 60.0 -- 6 / (3 + 6 + 1)
US 3 C3 1 10.0 -- 1 / (3 + 6 + 1)
使用SUM OVER()
然后将code\u计数
除以每个月的总和
select country , month , code , code_count ,
(code_count / sum(code_count) over(partition by month)) * 100 as percentage
From youtable
在内部查询中按国家/地区和月份分组,并在外部查询中使用每个组的总和
SQL Fiddle:
select t.country, t.month, t.code, t.code_count,
100 * t.code_count / cast( x.scc as float) as percentage
from t
left join
(
select country, month, sum(code_count) as scc
from t
group by country, month
) x
on x.month = t.month