现在有一个要求,
现有table1
客户编号 条码号 起度
01 130535826 5
02 130535827 12
02 130535828 8
02 130535829 21
03 130535830 92怎样形成表table2
客户编号 条码号1 起度1 条码号2 起度2 条码号3 起度3
01 130535826 5
02 130535827 12 130535828 8 130535829 21
03 130535830 92
一个朋友问得,没做出来,一开始以为是行列转置,不过细想不是,希望大家帮忙。谢谢。
现有table1
客户编号 条码号 起度
01 130535826 5
02 130535827 12
02 130535828 8
02 130535829 21
03 130535830 92怎样形成表table2
客户编号 条码号1 起度1 条码号2 起度2 条码号3 起度3
01 130535826 5
02 130535827 12 130535828 8 130535829 21
03 130535830 92
一个朋友问得,没做出来,一开始以为是行列转置,不过细想不是,希望大家帮忙。谢谢。
go
create table [table1]([客户编号] varchar(2),[条码号] int,[起度] int)
insert [table1]
select '01',130535826,5 union all
select '02',130535827,12 union all
select '02',130535828,8 union all
select '02',130535829,21 union all
select '03',130535830,92select *,id=identity(int,1,1) into # from table1declare @sql varchar(8000)
select
@sql=isnull(@sql+',','')
+'max(case when px='+ltrim(px)+' then ltrim(条码号) else '''' end) as [条码号'+ltrim(px)+'],'
+'max(case when px='+ltrim(px)+' then ltrim(起度) else '''' end) as [起度'+ltrim(px)+']'
from
(select distinct px=(select count(1)+1 from # where 客户编号=t.客户编号 and id<t.id) from # t) ttset @sql='select 客户编号,'
+@sql
+' from (select *,px=(select count(1)+1 from # where 客户编号=t.客户编号 and id<t.id) from # t) tt'
+' group by 客户编号'--print @sqlexec (@sql)drop table #,table1--测试结果:
/*
客户编号 条码号1 起度1 条码号2 起度2 条码号3 起度3
---- ------------ ------------ ------------ ------------ ------------ ------------
01 130535826 5
02 130535827 12 130535828 8 130535829 21
03 130535830 92 */
条码号1=(select max(条码号) from tb where 客户编号=a.客户编号 and 客户编号='01'),
起度1=(select max(起度) from tb where 客户编号=a.客户编号 and 客户编号='01'),
条码号2=(select max(条码号) from tb where 客户编号=a.客户编号 and 客户编号='02'),
起度2=(select max(起度) from tb where 客户编号=a.客户编号 and 客户编号='02'),
条码号3=(select max(条码号) from tb where 客户编号=a.客户编号 and 客户编号='03'),
起度3=(select max(起度) from tb where 客户编号=a.客户编号 and 客户编号='03'),
from tb a
group by 客户编号
没测试...
大概是这样的
只适合有三个customer,
如果很多客户的话,则需要使用动态SQL,行转列