标签:else shu inf 需要 create 列转行 float bsp sele
先建一个新表:
CREATE TABLE [StudentScores] ( [UserName] NVARCHAR(20), --学生姓名 [Subject] NVARCHAR(30), --科目 [Score] FLOAT, --成绩 ) INSERT INTO [StudentScores] SELECT ‘Nick‘, ‘语文‘, 80 INSERT INTO [StudentScores] SELECT ‘Nick‘, ‘数学‘, 90 INSERT INTO [StudentScores] SELECT ‘Nick‘, ‘英语‘, 70 INSERT INTO [StudentScores] SELECT ‘Nick‘, ‘生物‘, 85 INSERT INTO [StudentScores] SELECT ‘Kent‘, ‘语文‘, 80 INSERT INTO [StudentScores] SELECT ‘Kent‘, ‘数学‘, 90 INSERT INTO [StudentScores] SELECT ‘Kent‘, ‘英语‘, 70 INSERT INTO [StudentScores] SELECT ‘Kent‘, ‘生物‘, 85
第一种方法:
SELECT UserName, MAX(CASE Subject WHEN ‘语文‘ THEN Score ELSE 0 END) AS ‘语文‘, MAX(CASE Subject WHEN ‘数学‘ THEN Score ELSE 0 END) AS ‘数学‘, MAX(CASE Subject WHEN ‘英语‘ THEN Score ELSE 0 END) AS ‘英语‘, MAX(CASE Subject WHEN ‘生物‘ THEN Score ELSE 0 END) AS ‘生物‘ FROM dbo.[StudentScores] GROUP BY UserName
第二种方法:
SELECT * FROM StudentScores--第一步 pivot ( sum(Score) ----第三步 for Subject in (语文,数学,英语,生物))---第二步 as 成绩
第一步:从数据源查询数据
第二步:行转列的列名,将哪一列的数据转为列名
第三步:新的列名需要显示的值
跟第一种方法结果一致。
方法参考以下链接:
https://www.cnblogs.com/kerrycode/archive/2010/07/28/1786547.html
https://www.jianshu.com/p/8f929264995e
标签:else shu inf 需要 create 列转行 float bsp sele
原文地址:https://www.cnblogs.com/wwHww/p/13677210.html