日期:2014-05-17 浏览次数:20404 次
create table #tt2(DS int,DT date,CS float(8),OP float(8))
insert into #tt2 values ('420','2009-01-01','165','-7490')
insert into #tt2 values ('420','2008-01-01','168','-4902')
declare @sql varchar(max)
set @sql='select DS'
select @sql=@sql+',max(case when rowid='+ltrim(rowid)+' then DT else '''' end) as [DT'+ltrim(rowid)+']
,max(case when rowid='+ltrim(rowid)+' then CS else '''' end) as [CS'+ltrim(rowid)+']
,sum(case when rowid='+ltrim(rowid)+' then OP else '''' end) as [OP'+ltrim(rowid)+']'
from (select distinct rowid from (select (select count(distinct DT) from #tt2 where DS=t.DS and DT<=t.DT) rowid
from #tt2 t) a) b
set @sql=@sql+' from (select * , (select count(distinct DT) from #tt2 where DS=t.DS and DT<=t.DT) rowid
from #tt2 t ) t group by DS order by DS'
--print @sql
exec(@sql)
/*
DS DT1 CS1 OP1 DT2 CS2 OP2 DT3 CS3 OP3
----------- ---------- ------------- ---------------------- ---------- ------------- ---------------------- ---------- ------------- ----------------------
420