我有这个查询
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
列中按天分组答案 0 :(得分:0)
首先,您必须安装tablefunc
扩展程序。从版本9.1开始,您可以使用create extension:
CREATE EXTENSION tablefunc;
select * from crosstab (
select shop, date, SUM(amount)
from sales
group by shop
'select date from sales order by 1')
AS ct(shop: text, '2012-08-1' text, '2012-08-2' text, '2012-08-3' text)