postgres tablefunc,按产品分组的销售数据,具有月份的交叉表

时间:2019-05-03 17:14:06

标签: postgresql

大约tablefunccrosstab的TIL。起初,我想“按列对数据进行分组”,但这实际上没有任何意义。

我的产品销售情况如下

product_id | units   |  date
-----------------------------------
10         | 1          | 1-1-2018
10         | 2          | 2-2-2018
11         | 3          | 1-1-2018
11         | 10         | 1-2-2018
12         | 1          | 2-1-2018
13         | 10         | 1-1-2018
13         | 10         | 2-2-2018

我想生成一个以月为列的产品表

product_id | 01-01-2018 | 02-01-2018 | etc.
-----------------------------------
10         | 1          | 2
11         | 13         | 0
12         | 0          | 1
13         | 20         | 0

首先,我将按月份分组,然后对产品进行反转和分组,但是我不知道该怎么做。

1 个答案:

答案 0 :(得分:1)

enabling the tablefunc extension之后,

SELECT product_id, coalesce("2018-1-1", 0) as "2018-1-1"
    , coalesce("2018-2-1", 0) as "2018-2-1"
FROM crosstab(
   $$SELECT product_id, date_trunc('month', date)::date as month, sum(units) as units
    FROM   test
    GROUP BY product_id, month
    ORDER BY 1$$ 

  , $$VALUES ('2018-1-1'::date), ('2018-2-1')$$
   ) AS ct (product_id int, "2018-1-1" int, "2018-2-1" int);

收益

| product_id | 2018-1-1 | 2018-2-1 |
|------------+----------+----------|
|         10 |        1 |        2 |
|         11 |       13 |        0 |
|         12 |        0 |        1 |
|         13 |       10 |       10 |