日期:2014-05-17  浏览次数:20357 次

行转列后为何数值负数变成0了
有如下一表,需要行转列,但为何数值负数变成0了??
DS      DT              CS      OP
420 2009-01-01 165.0 -7490.0
420 2008-01-01 168.0 -4902.0

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)+']
,max(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'
exec(@sql)
------解决方案--------------------
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