TSQL 列到行

TSQL Columns to rows

我有以下 table 列(带有示例数据)

[Member_ID] - [GM1] - [GM2] ... [GM12] - [CATEGORY]
165 - 30 - 50 ... 40 - Products
165 - 70 - 60 ... 70 - Service
189 - 50 - 60 ... 50 - Products
189 - 40 - 30 ... 40 - Service

每个 GM 列代表每个月。

最后我想要这样的东西

[MemberID] - [GMP] - [GMS] - [MonthNumbr]
165 - 30 - 70 - 1
165 - 50 - 60 - 2
189 - 50 - 40 - 1
...
165 - 40 - 70 - 12
189 - 50 - 40 - 12

其中 GMP 是该月类别产品的 GM,GMS 是该月服务的 GM

我试过 unpivot 和交叉应用,但我认为这超出了我的经验并且一直卡住。

提前致谢!

我喜欢使用 outer apply 来达到这个目的。 . .那么聚合有帮助:

select v.member_id, v.monthnumber,
       max(case when category = 'products' then gm end) as gmp,
       max(case when category = 'service' then gm end) as gms
from t outer apply
     (values (t.member_id, 1, t.gm1, t.category),
             (t.member_id, 2, t.gm2, t.category),
              . . .
     ) v(member_id, monthnumber, gm, category)
group by v.member_id, v.monthnumber;

编辑:

在子查询中进行聚合可能更有效:

select v.*
from t outer apply
     (select v.member_id, v.monthnumber,
             max(case when category = 'products' then gm end) as gmp,
             max(case when category = 'service' then gm end) as gms
      from (values (t.member_id, 1, t.gm1, t.category),
                   (t.member_id, 2, t.gm2, t.category),
                   . . .
           ) v(member_id, monthnumber, gm, category)
     ) v;

(由于聚合算法的性质,一堆小聚合应该比一个大聚合更有效。)