大纲


    首页 sql案例 详情
    一种计算指标竖表的方式

    通过 聚合函数 + case when + explode的方式简洁快速实现多指标竖表的计算,避免冗余的union all

    背景

    比如,要从一张表根据不同的条件加工出不同的指标,还要求指标不能以单独的列存在,要合并在同一列,然后通过指标标签区分的指标竖表形式,有时我们会采用union的方式,如下

    select 维度
        ,sum(指标列) as 指标1
    from 表
    where 条件1
    group by 维度
    union all 
    select 维度
        ,sum(指标列) as 指标2
    from 表
    where 条件2
    group by 维度
    union all 
    select 维度
        ,sum(指标列) as 指标3
    from 表
    where 条件3
    group by 维度
    union all 
    select 维度
        ,sum(指标列) as 指标4
    from 表
    where 条件4
    group by 维度
    

    这样写起来会很繁琐,一点都不简洁

    简洁写法

    采用 聚合函数(case when) 行转列的方式将指标值一次性计算出来,然后用caoncat_ws函数将其拼接,然后再用explode侧视图将其进行列转行

    select t.维度
        ,split(tt.kpi,',')[0] as 指标名称
        ,split(tt.kpi,',')[1] as 指标值
    from(
        select 维度
            concat_ws('-'
                ,concat_ws(',','指标1',sum(case when 条件1 then 指标列 else 0 end))
                ,concat_ws(',','指标2',sum(case when 条件2 then 指标列 else 0 end))
                ,concat_ws(',','指标3',sum(case when 条件3 then 指标列 else 0 end))
                ,concat_ws(',','指标4',sum(case when 条件4 then 指标列 else 0 end))
            ) as kpis
        from 表
        group by 维度
    ) t explode(split(t.kpis,'-')) tt as kpi
    
    评论
    您尚未登录,请 登录 后评论
    共 0 条评论 | 欢迎尬评