Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql Postgres:组查询_Sql_Postgresql - Fatal编程技术网

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