使用TSQL来UNPIVOT简单的总计......甚至有可能吗?

时间:2019-03-27 14:10:15

标签: sql tsql sum unpivot aggregates

在将某些数据加载到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命令,但无法找出使用它的正确方法。

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

1 个答案:

答案 0 :(得分:3)

您无需执行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]);