这个行转列的SQL该怎么改?
表结构
我原本的SQL
select RecordTime ,
[测点0]=max(CASE WHEN [Spotid]=0 THEN RecordValue else 0 end ) ,
[测点1]=max(CASE WHEN [Spotid]=1 THEN RecordValue else 0 end ) ,
[测点2]=max(CASE WHEN [Spotid]=2 THEN RecordValue else 0 end )
from History_Record group by RecordTime
convert(int , RecordValue)
select RecordTime ,
[测点0]=max(CASE WHEN [Spotid]=0 THEN cast(RecordValue as int) else 0 end ) ,
[测点1]=max(CASE WHEN [Spotid]=1 THEN cast(RecordValue as int) else 0 end ) ,
[测点2]=max(CASE WHEN [Spotid]=2 THEN cast(RecordValue as int) else 0 end )
from History_Record
group by RecordTime
create index ix_History_Record on History_Record(RecordTime,Spotid,RecordValue)
12345678910111213141516171819202122 if exists(select 1 from sys.tables where name='test20130507') drop table test20130507 go create table test20130507(a varchar(20),b varchar(20),c varchar(20)) insert into test20130507 select '20130508','8:00~9:00','张三' union allselect '20130508','9:00~10:00','测试' union allselect '20130509','8:00~9:00','李四' union allselect '20130509','8:00~9:00','再测' union allselect '20130509','9:00~10:00','再测1' union allselect '20130609','9:00~10:00','再测1'go declare @sql varchar(max)=''select @sql=@sql+',max(case when a='''+a+''' then c else null end)as '''+a+'''' from (select distinct a from test20130507)a exec ('select b'+@sql+' from (select distinct a,b, c=stuff((select '',''+c from test20130507 where a.a=a and a.b=b for xml path('''')),1,1,'''') from test20130507 a)a group by b')
if exists(select 1 from sys.tables where name='test20130507')
drop table test20130507
go
create table test20130507(a varchar(20),b varchar(20),c varchar(20))
insert into test20130507
select '20130508','8:00~9:00','张三' union all
select '20130508','9:00~10:00','测试' union all
select '20130509','8:00~9:00','李四' union all
select '20130509','8:00~9:00','再测' union all
select '20130509','9:00~10:00','再测1' union all
select '20130609','9:00~10:00','再测1'
go
declare @sql varchar(max)=''
select @sql=@sql+',max(case when a='''+a+''' then c else null end)as '''+a+''''
from (select distinct a from test20130507)a
exec ('select b'+@sql+'
from (select distinct a,b,
c=stuff((select '',''+c from test20130507 where a.a=a and a.b=b for xml path('''')),1,1,'''')
from test20130507 a)a group by b')