【问题标题】:Grouping multiple lines onto one in Oracle SQL在 Oracle SQL 中将多行分组为一行
【发布时间】:2021-03-26 15:56:48
【问题描述】:

我怎样才能让图 1 中的数据集看起来像图 2 中的数据。基本上,我不想将每次购买都放在自己的行上,而是按名称分组,并将所有购买的人放在一行上。他们最多可以购买 5 件商品,而我的数据库大约有 3000 万行的购买记录。

P.S 日期顺序并不重要

【问题讨论】:

    标签: sql oracle aggregate grouping


    【解决方案1】:

    您可以将PIVOTrow_number 一起使用,如下所示:

    Select * from 
       (select t.*,
               row_number() over (partition by name order by date_purchased) rn
          from your_table t
      ) PIVOT
    (Max(item_purchased), max(date_purchased) For rn in (1,2,3));
    

    【讨论】:

      【解决方案2】:

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

      select name,
             max(case when seqnum = 1 then item end) as item_1,
             max(case when seqnum = 1 then date end) as date_1,
             max(case when seqnum = 2 then item end) as item_2,
             max(case when seqnum = 2 then date end) as date_2,
             max(case when seqnum = 3 then item end) as item_3,
             max(case when seqnum = 3 then date end) as date_3
      from (select t.*,
                   row_number() over (partition by name order by date asc) as seqnum
            from t
           ) t
      group by name;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-11
        • 1970-01-01
        • 1970-01-01
        • 2021-10-20
        • 2020-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多