sql—在oracle中一行显示多行数据

tag5nh1u  于 2021-07-29  发布在  Java
关注(0)|答案(3)|浏览(532)

在我的表中,每个名字都有3个条目以及action/date,如图所示

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
6gpjuf90

6gpjuf901#

可以使用条件聚合:

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;
d4so4syb

d4so4syb2#

您还可以使用pivot query做一些简短的操作:

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)
)
wtlkbnrh

wtlkbnrh3#

你可以用 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

相关问题