TSQL列到行
我有以下表格列(带有示例数据) 每个GM栏是针对每个月的 最后我想要这样的东西TSQL列到行,sql,sql-server,tsql,unpivot,Sql,Sql Server,Tsql,Unpivot,我有以下表格列(带有示例数据) 每个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是当月类别产品的总经理,GMS是当月服务的总经理 我尝试过取消PIVOT和交叉申请,但我认为这已经超出了我的经验,并且一直被卡住
[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是当月类别产品的总经理,GMS是当月服务的总经理
我尝试过取消PIVOT和交叉申请,但我认为这已经超出了我的经验,并且一直被卡住
提前谢谢 为此,我喜欢使用
外部应用
。然后,聚合有助于:
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;
(由于聚合算法的性质,一组小聚合应该比一个大聚合更有效。)
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;