我有一个带有值
的临时表select distinct sub from #t
给了我值
1-aaa
2-bbb
3-ccc
....
so on
然后我正在做以下
select fullname,
max(case when sub='aaa' then score end) 'aaa',
max(case when sub='bbb' then score end) 'bbb',
max(case when sub='ccc' then score end) 'ccc'
from #t
group by fullname
,这给出了
的结果fullname - aaa - bbb - ccc
fn1 - 15 - 18 - 21
fn2 - 18 - 23 - 33
fn3 - xx - yy - zz
问题是#t可能包含多达100个“名称”
这是我不能做的事情
有没有办法改变部分
max(case when sub='aaa' then score end) 'aaa'
基于来自#t?
的valeus的for / each like循环感谢
答案 0 :(得分:1)
然而,在动态SQL上,这是一个为您动态执行此操作的解决方案:
CREATE TABLE #T (FullName varchar(15),
sub char(3),
score int);
INSERT INTO #T
VALUES ('Joe Bloggs','aaa',17),
('Joe Bloggs','bbb',9),
('Joe Bloggs','ccc',24),
('Joe Bloggs','eee',14),
('Joe Bloggs','fff',12),
('Jane Smith','aaa',2),
('Jane Smith','ccc',12),
('Jane Smith','ddd',15),
('Jane Smith','eee',19),
('Jane Smith','ggg',21);
GO
DECLARE @SQL nvarchar(MAX);
SET @SQL = N'
SELECT Fullname,' + NCHAR(10) + STUFF((SELECT DISTINCT N',' + NCHAR(10) + N'MAX(CASE sub WHEN ''' + REPLACE(sub,N'''',N'''''') + N''' THEN score END) AS ' + QUOTENAME(sub) + N''
FROM #T
FOR XML PATH(N'')),1,2,N'') + '
FROM #T
GROUP BY Fullname;';
PRINT @SQL;
EXEC sp_executesql @SQL;
GO
DROP TABLE #t;
如果您不明白这一点,请询问。