对 postgresql 9.6 中的列集进行总和值分组

sum values grouping sets of columns in postgresql 9.6

CREATE TABLE products(
 id integer,
 country_id integer,
 category_id smallint,
 product_count integer
);

INSERT INTO products VALUES 
(1,12,1,2),
(2,12,1, 4),
(3,12,2,1),
(4,45,5,2),
(5,45,5,1),
(6,45,8,5),
(7,3,1,3),
(8,3,1,3)

-----------------------------------------------------
id | country_id | category_id | product_count
-----------------------------------------------------
1      12              1               2
2      12              1               4
3      12              2               1
4      45              5               2
5      45              5               1
6      45              8               5
7       3              1               3
8       3              1               3

我想看到的是这样,我想通过在每个分组 country_id;

下分组 category_id 来求和 product_counts
---------------------------------------------------------------------
id | country_id | category_id | product_count | total_count
---------------------------------------------------------------------
1      12             1              2               6
2      12             1              4               6
3      12             2              1               1
4      45             5              2               3
5      45             5              1               3
6      45             8              5               5
7       3             1              3               6
8       3             1              3               6

我试过了,但没用。这并不能解决问题并为每个分组 category_id;

带来 product_count 的总和值
SELECT *,SUM(r.product_count) as sum FROM (
    SELECT  id,
            country_id, 
            category_id, 
            product_count
        FROM products 
) r
GROUP BY r.country_id,r.category_id,r.product_count, r.id
ORDER BY r.country_id , r.category_id, r.product_count;

我按 country_id、category_id 分组以获得请求的结果:

et=# select *,sum(product_count) over (partition by country_id,category_id) from products order by id;
 id | country_id | category_id | product_count | sum
----+------------+-------------+---------------+-----
  1 |         12 |           1 |             2 |   6
  2 |         12 |           1 |             4 |   6
  3 |         12 |           2 |             1 |   1
  4 |         45 |           5 |             2 |   3
  5 |         45 |           5 |             1 |   3
  6 |         45 |           8 |             5 |   5
  7 |          3 |           1 |             3 |   6
  8 |          3 |           1 |             3 |   6
(8 rows)