现我有一视图内数据如下:
ID 同一率 标示号
a1 100 1
a1 98.2 2
a1 99 3
a1 78 4
a2 44 1
a2 78 2
a2 98 3
a2 79 4
...现在我想通过SQL语句得到
ID 同一率1 同一率2 同一率3 同一率4
a1 100 98.2 99 78
a2 44 78 98 79
...
就是把视图的标示号这列1、2、3、4转化为表头(横向)SQL语句该如何写?
ID 同一率 标示号
a1 100 1
a1 98.2 2
a1 99 3
a1 78 4
a2 44 1
a2 78 2
a2 98 3
a2 79 4
...现在我想通过SQL语句得到
ID 同一率1 同一率2 同一率3 同一率4
a1 100 98.2 99 78
a2 44 78 98 79
...
就是把视图的标示号这列1、2、3、4转化为表头(横向)SQL语句该如何写?
insert into #
select 'a1', 100, 1
union all select 'a1', 98.2, 2
union all select 'a1', 99, 3
union all select 'a1', 78, 4
union all select 'a2', 44, 1
union all select 'a2', 78, 2
union all select 'a2', 98, 3
union all select 'a2', 79, 4--...--现在我想通过SQL语句得到
--ID 同一率1 同一率2 同一率3 同一率4
--a1 100 98.2 99 78
--a2 44 78 98 79select * from #
declare @sql varchar(8000)
select @sql=''
select @sql=@sql+',(select 同一率 from # where id=a.id and 标示号='+cast(标示号 as nvarchar(10))+')as 同一率'+cast(标示号 as nvarchar(10))
from # group by 标示号
select @sql='select a.id '+@sql+' from # a group by id'
print @sql
exec(@sql)
drop table #
a1 100 1
a1 98.2 2
a1 99 3
a1 78 4
a2 44 1
a2 78 2
a2 98 3
a2 79 4
...select 'a1',100,1
union all select 'a1',98.2,2
union all select 'a1',99,3
union all select 'a1',78,4
union all select 'a2',44,1
union all select 'a2',78,2
union all select 'a2',98,3
union all select 'a2',79,4.....
有N多条记录,我都得这么写吗?
select @sql=''
select @sql=@sql+',(select 同一率 from 表名 where id=a.id and 标示号='+cast(标示号 as nvarchar(10))+')as 同一率'+cast(标示号 as nvarchar(10))
from 表名 group by 标示号
select @sql='select a.id '+@sql+' from 表名 a group by id'
print @sql
exec(@sql)你直接执行这个就可以了