将分类列拆分为SQL

时间:2018-01-11 20:35:32

标签: sql sql-server split

我有一个由以下代码生成的玩具数据集:

declare @tbl table (year int, month int, property varchar(4), nights varchar(4), LOS int) insert into @tbl (year, month, property, nights, LOS) VALUES (2017, 1, 'VA', '1', 33) insert into @tbl (year, month, property, nights, LOS) VALUES (2017, 1, 'VA', '2', 43) insert into @tbl (year, month, property, nights, LOS) VALUES (2017, 1, 'VA', '3', 51) insert into @tbl (year, month, property, nights, LOS) VALUES (2017, 1, 'VA', '4', 27) insert into @tbl (year, month, property, nights, LOS) VALUES (2017, 1, 'VA', '5+', 82) insert into @tbl (year, month, property, nights, LOS) VALUES (2017, 1, 'PZ', '1', 37) insert into @tbl (year, month, property, nights, LOS) VALUES (2017, 1, 'PZ', '2', 63) insert into @tbl (year, month, property, nights, LOS) VALUES (2017, 1, 'PZ', '3', 41) insert into @tbl (year, month, property, nights, LOS) VALUES (2017, 1, 'PZ', '4', 67) insert into @tbl (year, month, property, nights, LOS) VALUES (2017, 1, 'PZ', '5+', 52)

enter image description here

我想将列property拆分为property_VAproperty_PZ列,如下所示:

enter image description here

另一个问题是,如何添加一个名为total的新行,只能获得LOS_VALOS_PZ的总和。我不确定SQL可以做这些事情

1 个答案:

答案 0 :(得分:2)

一种选择是使用PIVOT,例如

    SELECT  year ,
            month ,
            nights ,
            'VA' Property_VA ,
            VA LOS_VA,
            'PZ' Property_PZ ,
            PZ LOS_PZ
    FROM    ( SELECT    *
              FROM      @tbl
            ) TBL PIVOT ( SUM(LOS) FOR property IN ( VA, PZ ) ) PVT

结果

    year        month       nights Property_VA LOS_VA          Property_PZ LOS_PZ
    ----------- ----------- ------ ----------- ----------- ----------- -----------
    2017        1           1      VA          33              PZ          37
    2017        1           2      VA          43              PZ          63
    2017        1           3      VA          51              PZ          41
    2017        1           4      VA          27              PZ          67
    2017        1           5+     VA          82              PZ          52

    (5 row(s) affected)