日期:2014-05-17 浏览次数:20769 次
--CREATE TABLE test (NAME VARCHAR(10),aihao VARCHAR(20))
--INSERT INTO test
--SELECT '张三', '爱唱歌'
--UNION ALL
--SELECT '张三', '爱跳舞'
--UNION ALL
--SELECT '张三', '爱打球'
--UNION ALL
--SELECT '李四', '爱跳舞'
--UNION ALL
--SELECT '李四', '爱打球'
--SELECT * FROM test
DECLARE @s NVARCHAR(4000)
SET @s = ''
SELECT @s = @s + ',' + QUOTENAME('aihao') + '=max(case when [aihao]='
+ QUOTENAME(aihao, '''') + ' then [aihao] else '''' end)'
FROM test
GROUP BY aihao
EXEC('select [name]'+@s+' from test group by [name]')
/*
name aihao aihao aihao
---------- -------------------- -------------------- --------------------
李四 爱打球 爱跳舞
张三 爱唱歌 爱打球 爱跳舞
(2 行受影响)
*/