【问题标题】:SQL Query to combine multiple rows into one based on ID while keeping other value in the same row?SQL Query 根据 ID 将多行合并为一行,同时将其他值保留在同一行中?
【发布时间】:2020-07-31 11:17:49
【问题描述】:

首先,我一直在寻找这个。

我有一张看起来有点像这样的桌子:

ID        Expenditure  MonthYear
1A        1,000        122019
1A        1,500        012020
1B        1,900        122019
1C        2,400        122019
1B        2,400        012020
1C        900          012020
1A        800          022020

由于行可以达到数千,并且某些 ID 重复了数十次,我想将具有不同 ID 的那些组合成一行并添加保留其中所有信息的列。我想让表格看起来像这样:

ID        Expenditure_1  MonthYear_1 Expenditure_2 MonthYear_2  Expenditure_3   MonthYear_3
1A        1,000          122019      1,500         012020       800             022020
1B        1,900          122019      2,400         012020       Null            Null
1C        2,400          122019      900           012020       Null            Null

在 Impala 上使用 SQL 解决此问题的最佳方法是什么? 谢谢。

【问题讨论】:

    标签: sql cloudera impala


    【解决方案1】:

    可以使用条件聚合和row_number():

    select id,
           max(case when seqnum = 1 then expenditure end) as expenditure_1,
           max(case when seqnum = 1 then monthyear end) as monthyear_1,
           max(case when seqnum = 2 then expenditure end) as expenditure_2,
           max(case when seqnum = 2 then monthyear end) as monthyear_2,
           max(case when seqnum = 3 then expenditure end) as expenditure_3,
           max(case when seqnum = 3 then monthyear end) as monthyear_3
    from (select t.*,
                 row_number() over (partition by id order by right(monthyear, 4), left(monthyear, 2)) as seqnum
          from t
         ) t
    group by id;
    

    【讨论】:

      猜你喜欢
      • 2015-11-08
      • 2012-11-04
      • 1970-01-01
      • 1970-01-01
      • 2013-05-24
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 2018-06-13
      相关资源
      最近更新 更多