【问题标题】:Using TSQL to UNPIVOT simple aggregated totals...is this even possible?使用 TSQL 对简单的汇总总计进行 UNPIVOT……这甚至可能吗?
【发布时间】:2019-03-27 14:10:15
【问题描述】:

我试图在将某些数据加载到 Microsoft PowerBI 之前对其执行简单的反透视。由于 PowerBI 报表必须使用 DirectQuery,因此不能在查询编辑器中使用“Unpivot”。因此,这似乎可以在加载的初始 SQL 中完成。

select
     sum(case when cw.State = 'WORK' then 1 else null end) [Work]
    ,sum(case when cw.State = 'OUT' then 1 else null end)  [Out]
    ,sum(case when cw.State = 'POST' then 1 else null end) [Post]
from CurrentWork cw

这段代码输出:

Work  Out  Post
----  ---  ----
  5    3    21

但我希望输出显示如下:

Event  Amount
-----  ------
Work   5
Out    3
Post   21

我认为我需要使用 UNPIVOT TSQL 命令,但想不出正确的使用方法。

这是可能的,还是我从错误的方向解决这个问题?

【问题讨论】:

    标签: sql tsql sum unpivot aggregates


    【解决方案1】:

    你不需要做UNPIVOT,你想要聚合:

    select status, count(*)
    from CurrentWork 
    group by status;
    

    如果汇总了以上数据,那么您可以将subuqerycteapply 一起使用:

    with t as (
         select sum(case when cw.State = 'WORK' then 1 else null end) [Work]
                sum(case when cw.State = 'OUT' then 1 else null end)  [Out]
                sum(case when cw.State = 'POST' then 1 else null end) [Post]
         from CurrentWork cw
    )
    select tt.Event, tt.[Amount]
    from t cross apply
         ( values ([Work], [Amount]), ([Out], [Amount]), ([Post], [Amount]) 
         ) tt(Event, [Amount]);
    

    【讨论】:

    • 哇...我是个白痴,如果我能让你用数字方式打我的脸,我会的。再次感谢让我成为 StackOverflow dummy。我很感激 Yogesh!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 2017-05-31
    • 1970-01-01
    • 2018-09-01
    相关资源
    最近更新 更多