【问题标题】:Split the categorical column into multiple columns in SQL在 SQL 中将分类列拆分为多列
【发布时间】:2018-01-11 20:35:32
【问题描述】:

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

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)

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

另一个问题是,我怎样才能追加一个名为total 的新行,以仅获得LOS_VALOS_PZ 的总和。我不确定 SQL 能不能做到这一点

【问题讨论】:

  • 你试过什么?结果与您的预期有何不同? Stack Overflow 不是代码编写服务。向我们展示您的尝试,我们可以帮助您找出为什么它不起作用。
  • 我明白,我知道如何在 R 中做到这一点,但我不知道如何在 SQL 中做到这一点,我正在寻找一些在 SQL 中类似的 rbind 函数。这就是我在这里寻求帮助的原因

标签: sql sql-server split


【解决方案1】:

一种选择是使用 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)

【讨论】:

  • 或者通过加入和分组
  • @Von 非常感谢,我没有说我们可以在 SQL 中做数据透视表,这非常强大。
  • @AkiraKaneshiro 很乐意为您提供帮助。
  • @VonAaron 我已经稍微修改了您的代码以获得我想要的结果。 SELECT year , month , property, [1], [2], [3], [4], [5+] FROM ( SELECT * FROM @tbl ) TBL PIVOT ( SUM(LOS) FOR nights IN ( [1], [2], [3], [4], [5+] ) ) PVT 其实我还有一个问题,我可以在每个属性的所有 LOS 总和中添加一个名为 total 的列吗?我正在考虑与 CTE 分组,然后加入数据透视表。但它对我不起作用。
  • @AkiraKaneshiro 是的,您可以,只需将所有夜晚的列加起来即可。示例 - drive.google.com/open?id=17Kcz-z_tUeYt28ppV7zo3Pa71xw--VfS
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-10
  • 1970-01-01
  • 1970-01-01
  • 2012-06-16
  • 1970-01-01
相关资源
最近更新 更多