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
以上所述是小編給大家介紹的SQL Server縱表與橫表相互轉換的實現方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對網站的支持!