阅读更多
-- 创建表
CREATE TABLE T_Score(
ScoreId INT IDENTITY (1,1) NOT NULL,
StuName NVARCHAR(50),
Subject NVARCHAR(50),
Score INT
)
-- 插入数据
INSERT INTO T_Score(StuName,Subject,Score)
SELECT '李四','英语',88 UNION ALL
SELECT '李四','语文',99 UNION ALL
SELECT '李四','化学',78 UNION ALL
SELECT '李四','历史',82 UNION ALL
SELECT '李四','物理',98 UNION ALL
SELECT '王五','英语',89 UNION ALL
SELECT '刘萍','英语',77 UNION ALL
SELECT '刘萍','语文',68 UNION ALL
SELECT '王六','英语',81 UNION ALL
SELECT '马林','英语',84
--行列转换(显示数据)
DECLARE @SQL VARCHAR(8000)
SET @SQL='SELECT StuName AS 姓名'
SELECT @SQL=@SQL+',SUM(CASE Subject WHEN '''+Subject+''' THEN Score ELSE 0 END) ['+Subject+']'
FROM (SELECT DISTINCT Subject FROM T_Score) AS tt
SELECT @SQL=@SQL+' FROM T_Score GROUP BY StuName'
EXEC(@SQL)
- 大小: 6.2 KB