【问题标题】:Postgresql transpose rows to columnsPostgresql 将行转置为列
【发布时间】: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


【解决方案1】:

首先,您必须安装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)

【讨论】:

    猜你喜欢
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 2012-05-24
    • 1970-01-01
    • 2023-03-27
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多