码迷,mamicode.com
首页 > 数据库 > 详细

SQL Server之纵表与横表互转

时间:2016-09-18 10:03:09      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/joesphos/p/5880354.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!