Postgres:组查询

时间:2015-08-06 12:56:32

标签: 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        3       C2     6
US        3       C3     1

我需要一个按code_countcountry分组的month百分比的查询。我期待以下输出:

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)

2 个答案:

答案 0 :(得分:1)

使用SUM OVER()查找每个code_count

month的总和

然后将code_count除以每个month

的总和
select country , month , code , code_count ,
       (code_count / sum(code_count) over(partition by month)) * 100 as percentage
From youtable

答案 1 :(得分:1)

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

在内部查询中按国家/地区分组,并使用每组sum查找外部查询中的百分比。

SQL小提琴:http://sqlfiddle.com/#!15/f4b5f/16