PIVOT和UNPIVOT
--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
SELECT name,scores FROM
(
SELECT *
FROM test
PIVOT ( SUM(scores) FOR name IN (成龙,莉莉,李连杰,周杰伦,周星驰,刘德华) )AS PVT
) AS selectt
UNPIVOT ( scores FOR name IN (成龙,莉莉,李连杰,周杰伦,周星驰,刘德华) )AS UNPVT
/*
name scores
成龙 150
莉莉 260
李连杰 200
周杰伦 230
周星驰 100
*/
/*
SELECT * FROM test PIVOT (SUM(scores) FOR NAME IN(成龙)) pvt
SELECT * FROM test1 UNPIVOT (scores for name IN (成龙,莉莉,李连杰,周杰伦,周星驰,刘德华)) unpit
*/
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
SELECT name,scores FROM
(
SELECT *
FROM test
PIVOT ( SUM(scores) FOR name IN (成龙,莉莉,李连杰,周杰伦,周星驰,刘德华) )AS PVT
) AS selectt
UNPIVOT ( scores FOR name IN (成龙,莉莉,李连杰,周杰伦,周星驰,刘德华) )AS UNPVT
/*
name scores
成龙 150
莉莉 260
李连杰 200
周杰伦 230
周星驰 100
*/
/*
SELECT * FROM test PIVOT (SUM(scores) FOR NAME IN(成龙)) pvt
SELECT * FROM test1 UNPIVOT (scores for name IN (成龙,莉莉,李连杰,周杰伦,周星驰,刘德华)) unpit
*/