日期:2014-05-17 浏览次数:20645 次
select traderid,materialid,zd1 as price,1 as [month] from traderpric union all select traderid,materialid,zd2,2 from traderpric union all select traderid,materialid,zd3,3 from traderpric union all select traderid,materialid,zd4,4 from traderpric union all select traderid,materialid,zd5,5 from traderpric union all select traderid,materialid,zd6,6 from traderpric union all select traderid,materialid,zd7,7 from traderpric union all select traderid,materialid,zd8,8 from traderpric union all select traderid,materialid,zd9,9 from traderpric union all select traderid,materialid,zd10,10 from traderpric union all select traderid,materialid,zd11,11 from traderpric union all select traderid,materialid,zd12,12 from traderpric
------解决方案--------------------
if object_id('traderprice') is not null drop table traderprice
go
create table traderprice(traderid int,materialid int,zd1 money,zd2 money,zd3 money,zd4 money,zd5 money,zd6 money,zd7 money,zd8 money,zd9 money,zd10 money,zd11 money,zd12 money)
go
insert into traderprice
select 1 , 3 , 1 ,1.5, 3 , 4 ,4.3,6, 7 ,8 ,9 ,10 ,11 ,12
go
declare @sql varchar(4000),@i int
set @i=1
while @i<=12
begin
set @sql=isnull(@sql+' union all ','')+'select traderid,materialid,zd'+cast(@i as varchar(2))+' as price,'+cast(@i as varchar(2))+' as [month] from traderprice'
set @i=@i+1
end
exec(@sql)
/*
traderid materialid price month
----------- ----------- --------------------- -----------
1 3 1.00 1
1 3 1.50 2
1 3 3.00 3
1 3 4.00 4
1 3 4.30 5
1 3 6.00 6
1 3 7.00 7
1 3 8.00 8
1 3 9.00 9
1 3 10.00 10
1 3 11.00 11
1 3 12.00 12
*/