--drop table test
CREATE TABLE test
(
name VARCHAR(12),
scores INT
)
INSERT INTO test
SELECT '周杰伦',230
UNION
SELECT '周星驰',100
UNION
SELECT '成龙',150
UNION
SELECT '李连杰',200
UNION
SELECT '莉莉',260
SELECT * FROM test
/*
name scores
成龙 150
莉莉 260
李连杰 200
周杰伦 230
周星驰 100
*/
SELECT 成龙,莉莉,李连杰,周杰伦,周星驰,刘德华
FROM test
PIVOT
(SUM(scores) FOR name IN (成龙,莉莉,李连杰,周杰伦,周星驰,刘德华) )AS PVT
/*
成龙 莉莉 李连杰 周杰伦 周星驰 刘德华
150 260 200 230 100 NULL
*/
--drop table test1
---动态列
DECLARE @col VARCHAR(8000)
--获取列
SET @col = ''
SELECT @col = @col + name + ','
FROM test
PRINT LEFT(@col, LEN(@col) - 1)
SET @col = LEFT(@col, LEN(@col) - 1)
/*
成龙,莉莉,李连杰,周杰伦,周星驰
*/
DECLARE @sql VARCHAR(8000)
SET @sql = 'SELECT ' + @col + '
FROM test
PIVOT
(SUM(scores) FOR name IN (' + @col + ') )AS PVT
'
EXEC (@sql)