简体   繁体   中英

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

What i want to see is like that, I want to sum product_counts by grouping category_id under every grouped country_id;

---------------------------------------------------------------------
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

I tried this, but it didn't help. This doesn't make the trick and bring summed value of product_count for each grouped category_id;

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;

I grouped by both country_id,category_id to get requested result:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM