1,縱表轉橫表 縱表結構 Table_A: 轉換後的結構: 縱表轉橫表的SQL示例: SELECT Name , SUM(CASE WHEN Course = N'語文' THEN Grade ELSE 0 END) AS Chinese , SUM(CASE WHEN Course = N'數學' ...
1,縱表轉橫表
縱表結構 Table_A:
轉換後的結構:
縱表轉橫表的SQL示例:
SELECT Name ,
SUM(CASE WHEN Course = N'語文' THEN Grade
ELSE 0
END) AS Chinese ,
SUM(CASE WHEN Course = N'數學' THEN Grade
ELSE 0
END) AS Mathematics ,
SUM(CASE WHEN Course = N'英語' THEN Grade
ELSE 0
END) AS English
FROM dbo.Table_A
GROUP BY Name
2,橫表轉縱表
橫表結構Table_B:
轉換後的表結構:
橫表轉縱表的SQL示例:
SELECT Name ,
'Chinese' AS Course ,
Chinese AS Score
FROM dbo.Table_B
UNION ALL
SELECT Name ,
'Mathematics' AS Course ,
Mathematics AS Score
FROM dbo.Table_B
UNION ALL
SELECT Name ,
'English' AS Course ,
English AS Score
FROM dbo.Table_B
ORDER BY Name ,
Course DESC