在SQL中进行透视

时间:2012-06-15 07:40:07

标签: sql-server-2008

我有

SalesOrderId    Partners    PartnerType
1                   A            1
1                   B            2
2                   X            1
2                   Y            2

我需要

SalesOrdeId Reseller    Distrubutor ResellerType    DistributorType
1              A              B           1                2
2              X              Y           1                2

N.B.~经销商类型= 1,经销商类型= 2

是否可以使用旋转来实现这一目标?

DDL

declare @t table(SalesOrderId int,Partners Varchar(10),PartnerType int)
Insert into @t values(1,'A',1),(1,'B',2),(2,'X',1),(2,'Y',2)
select *
From @t

由于

1 个答案:

答案 0 :(得分:1)

select SalesOrderId,
       max(case PartnerType when 1 then Partners end) as Reseller,
       max(case PartnerType when 2 then Partners end) as Distributor,
       1 as ResellerType,
       2 as DistributorType
from @t
group by SalesOrderId