SQL Server之纵表与横表互转

1,纵表转横表

纵表结构 Table_A:

美洲杯赌球 1

转换后的结构:

美洲杯赌球 2

纵表转横表的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:

美洲杯赌球 3

转换后的表结构:

美洲杯赌球 4

横表转纵表的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之纵表与横表互转

TAG标签: 美洲杯赌球
Ctrl+D 将本页面保存为书签,全面了解最新资讯,方便快捷。