【问题标题】:How to substract from one row the other ones in SQL Clickhouse如何从 SQL Clickhouse 中的一行中减去其他行
【发布时间】:2021-12-24 17:29:51
【问题描述】:

我对行的减法有疑问。 例如,执行此查询后:

select 
    case 
        when source in ('all') then 'all'
        when source in ('source1') then 'source1'
        when source in ('source2') then 'source2'
        when source in ('source3') then 'source3'
    end as source,
    
    sum(value) as sum
    
from table
group by 
    source

我有一张桌子:

source sum
all 100
source 1 1
source 2 1
source 3 1

并且我想将“all-source1-source2-source3”值为 100-1-1-1=97 的新行添加到此表中。你能帮帮我吗?

【问题讨论】:

    标签: sql rows clickhouse


    【解决方案1】:
    select (arrayJoin(flatten([sa, ss, sd])) as x).1 source, x.2 sum
    FROM (
           select groupArrayIf((source, sum), source='all') sa, 
                  groupArrayIf((source, sum), source!='all') ss,
                  [('diff', arraySum(sa.2) - arraySum(ss.2))] sd
           from (
                   select  'all'  source, 100 sum union all
                   select  'source 1', 1 union all
                   select  'source 2', 1 union all
                   select  'source 3', 1 
           )
        )
    
    ┌─source───┬─sum─┐
    │ all      │ 100 │
    │ source 1 │   1 │
    │ source 2 │   1 │
    │ source 3 │   1 │
    │ diff     │  97 │
    └──────────┴─────┘
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2010-10-29
    • 1970-01-01
    相关资源
    最近更新 更多