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

时间:2017-10-14 11:27:49

标签: sql postgresql window-functions 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;

1 个答案:

答案 0 :(得分:0)

我按country_id,category_id分组以获取请求的结果:

+----+------+-----------------------+-------+--------------+---+
| id | name | address               | phone | order_number |NID|
+----+------+-----------------------+-------+--------------+---|
|  1 | Joe  | Joes Address          | 1111  | 1390842      | 1 |
|  2 | Paul | Pauls Address         | 2222  | 9082309      | 2 |
|  3 | Greg | Gregs Address         | 3333  | 0928340      | 3 |
|  4 | Lucy | Lucys Address         | 4444  | 9028340      | 4 |
|  5 | Paul | Pauls Address         | 2222  | 8958399      | 2 |
|  6 | Tom  | Toms Address          | 5555  | 9084024      | 5 |
|  7 | Lucy | Lucys Another Address | 4444  | 9801983      | 4 |
|  8 | Paul | Pauls Another Address | 2222  | 0982304      | 2 |
+----+------+-----------------------+-------+--------------+---+