有1个table
PC_No software
A XP
A WINS
A RAR
B XP
B WINS
C 2000
C RAR
要得到如下结果:
PC_No. xp 2000 wins rar
A XP WINS RAR
B XP WINS
C 2000 RAR请问这个SQL刚刚学习!
PC_No software
A XP
A WINS
A RAR
B XP
B WINS
C 2000
C RAR
要得到如下结果:
PC_No. xp 2000 wins rar
A XP WINS RAR
B XP WINS
C 2000 RAR请问这个SQL刚刚学习!
create table #t (no varchar(10),software varchar(10))
insert into #t
select 'A' , 'XP'
union all
select 'A' , 'WINS'
union all
select 'A' , 'RAR'
union all
select 'B' ,'XP'
union all
select 'B' , 'WINS'
union all
select 'C' , '2000'
union all
select 'C' , 'RAR'declare @str varchar(8000)
set @str=''select distinct software into #x from #tselect @str=@str+',max(case when software='''
+software+''' then software else null end) as ['+ software + ']'
from #xselect @str
exec('select no'+@str+' from #t group by no' )
go
drop table #x
drop table #t
A XP
A WINS
A RAR
B XP
B WINS
C 2000
C RAR
PC_No. xp 2000 others(要求输出的表的格式已决定了)
A XP WINS RAR
B XP WINS
C 2000 RAR
,不好意思,第一次写这种SQL语句,没有任何基础,工作急求!
insert T select 'A' , 'XP'
union all select 'A', 'WINS'
union all select 'A', 'RAR'
union all select 'B' , 'XP'
union all select 'B', 'WINS'
union all select 'C', '2000'
union all select 'C', 'RAR'declare @sql varchar(8000)
set @sql=' select PC_No,'
select @sql=@sql+quotename(software)+'=max(case when software='+quotename(software, '''')+' then software else '''' end),' from T group by software
select @sql=left(@sql, len(@sql)-1), @sql=@sql+' from T group by PC_No '
exec(@sql)--result
PC_No 2000 RAR WINS XP
----- ---------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------
A RAR WINS XP
B WINS XP
C 2000 RAR
SET @SQL = 'SELECT PC_NO '
SELECT @SQL = @SQL + ',MAX(CASE SOFTWARE WHEN ''' +SOFTWARE +''' THEN SOFTWARE END) '+SOFTWARE
FROM (SELECT DISTINCT SOFTWARE FROM MY_TABLE3) SOFTWARE
SELECT @SQL = @SQL + ' FROM MY_TABLE3 GROUP BY PC_NO'
EXEC (@SQL)