sql server 2005 行列转置


  
  
原始数据:
转置后数据:
-- populate some test data
if object_id('tempdb..#tmp') is not null drop table #tmp
create table #tmp (
    ID int identity(1,1) not null,
    MainField varchar(100),
    ThatField int,
    ThatOtherField datetime
)

insert into #tmp (MainField, ThatField, ThatOtherField)
select 'A', 10, '1/1/2000' union all
select 'A', 20, '2/1/2000' union all
select 'A', 30, '3/1/2000' union all
select 'B', 10, '1/1/2001' union all
select 'B', 20, '2/1/2001' union all
select 'B', 30, '3/1/2001' union all
select 'B', 40, '4/1/2001' union all
select 'C', 10, '1/1/2002' union all
select 'D', 10, '1/1/2000' union all
select 'D', 20, '2/1/2000' --union all

-- pivot over multiple columns using the 1.1, 1.2, 2.1, 2.2 sequence trick
select
    MainField,
    max([1.1]) as ThatField1,
    max([1.2]) as ThatOtherField1,
    max([2.1]) as ThatField2,
    max([2.2]) as ThatOtherField2,
    max([3.1]) as ThatField3,
    max([3.2]) as ThatOtherField3,
    max([4.1]) as ThatField4,
    max([4.2]) as ThatOtherField4
from
(
    (
        select x.*,
            cast(row_number() over (partition by MainField order by ThatField) as varchar(2)) + '.1' as ThatFieldSequence,
            cast(row_number() over (partition by MainField order by ThatField) as varchar(2)) + '.2' as ThatOtherFieldSequence
        from #tmp x
    ) a
    pivot (
        max(ThatField) for ThatFieldSequence in ([1.1], [2.1], [3.1], [4.1])
    ) p1
    pivot (
        max(ThatOtherField) for ThatOtherFieldSequence in ([1.2], [2.2], [3.2], [4.2])
    ) p2
)ddd
group by
    MainField
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值