【问题标题】:Pivot or equivalent in clickhouseClickhouse 中的 Pivot 或等效项
【发布时间】:2020-08-30 01:33:00
【问题描述】:

我是 clickhouse 或任何柱状数据库的新手。我需要像在 sql-server、postgres 或任何其他基于行的 db 中一样旋转表。

我正在寻找一个通用的解决方案,但是这里示例的解决方案会很好。

表:存储

Tag  Slot  Reading  
---  ---- --------      
A     1     5 
B     1     6  
C     1     1  
A     2     2       
B     2     8
C     3     2
.
.
millions of rows

转置为:

Slot  A   B   C   and so on  
---   --  --  --       
1     5   6   1
2     2   8   -  
3     -   -   2  
.
. 
and so on

标签可以介于 100 到 1000 之间,槽位可以介于 1000 到 10000 之间。不过没关系。

我只需要使用 sql 来执行此操作。

谢谢。

【问题讨论】:

    标签: pivot-table clickhouse


    【解决方案1】:
    create table xxx (Tag String, Slot Int64, Reading Int64) Engine=Memory;
    insert into xxx values 
    ('A',1,5),
    ('B',1,6), 
    ('C',1,1),  
    ('A',2,2),  
    ('B',2,8),
    ('C',3,2)
    
    SELECT
        Slot,
        groupArray((Tag, Reading))
    FROM xxx
    GROUP BY Slot
    
    ┌─Slot─┬─groupArray(tuple(Tag, Reading))─┐
    │    3 │ [('C',2)]                       │
    │    2 │ [('A',2),('B',8)]               │
    │    1 │ [('A',5),('B',6),('C',1)]       │
    └──────┴─────────────────────────────────┘
    

    【讨论】:

    • 谢谢丹尼斯。这很快,而且似乎有效。我将尝试将其转换为传统的透视,即:转置列(此处标记)、行(此处读取)、值:聚合列(可能是另一列)和聚合公式。
    【解决方案2】:
    select Slot, 
           sumIf(Reading, Tag='A') A,
           sumIf(Reading, Tag='B') B,
           ...
    group by Slot
    

    select Slot, arrayReduce('sumMap', [(groupArray(tuple(Tag,Reading)) as a).1], [a.2])
    ...
    group by Slot
    

    select Slot, groupArray(tuple(Tag, Reading))
    from 
      (select Slot, Tag, sum(Reading) Reading
      ...
      group by Slot, Tag)
    group by Slot
    

    【讨论】:

    • 谢谢丹尼斯。我不想聚合阅读列,它只是在标签上转置,但是可能有聚合列,在这种情况下这应该可以工作。读数 col 可以是非数值。如果我们有 3 个以上的列,比如 value 是数字,我们需要对其进行聚合。此外,我们事先不知道标签,所以我认为选项 1 不起作用。
    • @Amit 我已经添加了一个答案。
    猜你喜欢
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    相关资源
    最近更新 更多