TSQL列到行

时间:2017-01-21 14:19:29

标签: sql sql-server tsql unpivot

我有以下表格列(包含样本数据)

[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是该月服务的总经理

我尝试了解开并交叉申请,但我认为这取决于我的经验并且不断陷入困境。

提前感谢!

1 个答案:

答案 0 :(得分:0)

我喜欢将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;

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