分组,然后将多行合并为一行

时间:2018-10-31 21:02:19

标签: sql postgresql group-by

我有一张这样的桌子:

group    subgroup     date           action
A         a           09/09/2017       ok
A         b           17/10/2018       ko
A         c           17/11/2018       wait
A         d           21/12/2018       no-action
B         e           11/12/2020       nok
B         f           13/11/2019       wait

因此对于这个集合,我只希望按组获得一行 因此,例如,组A包含一个带有“确定”的动作,我只想保留这一行

否则,如果集合中没有可以执行的操作,我需要将日期保留为最大日期

我尝试了很多事情,但无法达到预期效果,

group           date           action
    A          09/09/2017       ok
    B          11/12/2020       nok

2 个答案:

答案 0 :(得分:2)

您可以尝试使用ROW_NUMBER窗口功能。

CREATE TABLE T(
   "group" varchar(50),
   subgroup varchar(50),
   "date" date,
   action varchar(50)
);


insert into T values ('A','a','2017/09/09','ok');
insert into T values ('A','b','2018/10/17','ko');
insert into T values ('A','c','2018/11/17','wait');
insert into T values ('A','d','2018/12/21','no-action');
insert into T values ('B','e','2020/12/11','nok');
insert into T values ('B','f','2019/11/13','wait');

查询1

SELECT "group",date,"action" FROM (
    SELECT *,ROW_NUMBER() OVER(PARTITION BY "group" order by case when action = 'ok' then 1 else 2 end,date desc) rn
    FROM T
)t1
where rn = 1

Results

| group |       date | action |
|-------|------------|--------|
|     A | 2017-09-09 |     ok |
|     B | 2020-12-11 |    nok |

答案 1 :(得分:2)

您可以通过设置优先级来实现:

select t.*
from (select t.*,
             row_number() over (partition by group 
                                order by case when action = 'ok' then 1 else 2 end,
                                         date
                               ) as seqnum
      from t
     ) t
where seqnum = 1;