使用 TSQL 取消透视简单聚合总计.这甚至可能吗



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

这甚至可能吗,还是我从错误的方向处理这个问题?

不需要做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]);

最新更新