【发布时间】:2017-09-18 13:52:25
【问题描述】:
我有这个问题
select * from sales
shop | date | hour | row_no | amount
-----------+------------+-----------+--------+-----------
shop_1 | 2012-08-14 | 00:08:00 | P01 | 10
shop_2 | 2012-08-12 | 00:12:00 | O05 | 40
shop_2 | 2012-08-12 | 00:12:00 | A01 | 20
我有 1 百万行,我可以做这个查询
select shop, SUM(amount)
from sales
group by shop
shop | amount |
-----------+------------+
shop_1 | 5666 |
shop_2 | 4044 |
shop_3 4044 |
但我需要在专栏中度过几天,我不知道他们是否可以帮助我做到这一点
shop | 2012-08-1 | 2012-08-2 | 2012-08-3 |
-----------+------------+-----------+--------+-----------
shop_1 | 4005 | 5667 | 9987 |
shop_2 | 4333 | 4554 | 1234 |
shop_3 | 4555 | 6778 | 6677 |
将在行中按商店分组,在 postgresql 中按天分组
【问题讨论】:
-
搜索交叉表
-
他听说过一些交叉表,但有人知道如何使用它吗?
-
Cross tab 需要你知道生成的表格的尺寸。除非您知道自己有多少天或想要多少天,否则您不会知道这一点。你?你想要每一天还是一周,因为“每一天”需要动态的 sql 和交叉表。
-
同时检查github.com/hnsl/colpivot 可以发现列
标签: sql database postgresql pivot crosstab