[英]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
我想看到的是这样,我想通过将category_id分组到每个分组的country_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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.