【问题标题】:Display data from multiple row in one row in oracle在oracle中一行显示多行数据
【发布时间】:2020-11-19 00:54:33
【问题描述】:

如图所示,我的表格中的每个名称以及操作/日期都有 3 个条目

 id  | Name| Action    |  Date 
 1   | abc |  Insert   |  01-02-2020 
 1   | abc |  Edit     |  02-02-2020  
 1   | abc |  Delete   |  02-06-2020
 2   | xyz |  Insert   |  02-06-2020
 2   | xyz |  Edit     |  05-06-2020
 2   | xyz |  Delete   |  05-06-2020

我想将数据显示为

ID  | Name | C1    |      D1     |   C2      |     D2        |    C3     |   D3
1   | abc  | Insert|  01-02-2020 |  Edit     |  02-02-2020   |  Delete   |  02-06-2020
2   | xyz  | Insert|  02-06-2020 |  Edit     |  05-06-2020   |  Delete   |  05-06-2020

【问题讨论】:

  • MySQL 还是 Oracle?请仅标记您正在使用的一个数据库。
  • 考虑处理应用代码中数据显示的问题

标签: sql oracle oracle11g pivot


【解决方案1】:

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

select
    id,
    name,
    max(case when rn = 1 then action end) c1,
    max(case when rn = 1 then date end)   d1,
    max(case when rn = 2 then action end) c2,
    max(case when rn = 2 then date end)   d2,
    max(case when rn = 3 then action end) c3,
    max(case when rn = 3 then date end)   d3
from (
    select 
        t.*, 
        row_number() over(partition by id, name order by date) rn
    from mytable t
) t
group by id, name

【讨论】:

    【解决方案2】:

    您可以使用条件聚合:

    select id, name,
           max(case when seqnum = 1 then action end) as action_1,
           max(case when seqnum = 1 then date end) as date_1,
           max(case when seqnum = 2 then action end) as action_2,
           max(case when seqnum = 2 then date end) as date_2,
           max(case when seqnum = 3 then action end) as action_3,
           max(case when seqnum = 3 then date end) as date_3
    from (select t.*, row_number() over (partition by id, name order by date) as seqnum
          from t
         ) t
    group by id, name;
    

    【讨论】:

      【解决方案3】:

      您还可以使用数据透视查询来缩短一点:

      SELECT *
        FROM (SELECT dat.*, row_number() over(partition by id, name order by "DATE") rn FROM dat)
      pivot 
      (
         MAX(action) AS c,
         MAX("DATE") AS d
         FOR rn IN (1,2,3)
      )
      

      【讨论】:

        猜你喜欢
        • 2021-11-10
        • 2014-06-07
        • 1970-01-01
        • 2014-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-09
        • 1970-01-01
        相关资源
        最近更新 更多