毫无规律的表数据的行列转换方法!!

use test 

go

if object_id('test.dbo.tb') is not null drop table tb

-- 创建数据表

create table tb

(

message int,

time char(4),

orgid int

)

go

--插入测试数据

insert into tb select 123,2010,12

union all select 456,2010,12

union all select 789,2010,14

union all select 963,2010,15

union all select 345,2010,16

union all select 667,2010,16

union all select 423,2010,16

go

--代码实现

select * from tb

/*原数据

message time orgid

------------------------------

123 2010 12

456 2010 12

789 2010 14

963 2010 15

345 2010 16

667 2010 16

423 2010 16

(7 行受影响)

*/

declare @s varchar(max),@i int,@maxnum int,@str varchar(max)

select @i=0,@maxnum=max(num) from (select num=count(*) from tb group by orgid)t

while(@i<@maxnum)

begin

     select @s=isnull(@s+' when orgid='+rtrim(orgid)+' and idd='+rtrim(@i+1)+' then message' , 'case when                orgid='+rtrim(orgid)+' and idd='+rtrim(@i+1)+' then message')  from (select distinct orgid from tb)t

     select @s='message'+rtrim(@i)+'=max('+@s+' end),' +'time'+rtrim(@i)+'=max('+replace(@s,'message','time')+'      end)' ,@str=isnull(@str+','+@s,@s),@s=null,@i=@i+1

end

print @str

exec(';with t as (select idd=row_number()over(partition by orgid order by getdate()),* from tb) select orgid,'+@str+' from t group by orgid')

/*测试结果

orgid message0 time0 message1 time1 message2 time2

-------------------------------------------------------------------------------------------

12 123 2010 456 2010 NULL NULL

14 789 2010 NULL NULL NULL NULL

15 963 2010 NULL NULL NULL NULL

16 345 2010 667 2010 423 2010

(3 行受影响)

*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喜-喜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值