如何排除具有相似列的行?

How to exclude rows with similar columns?

有个table:

| date        | action | issue_id |
| 2020-12-14  | close  | 1        |
| 2020-12-15  | close  | 1        |
| 2020-12-16  | close  | 1        |
| 2020-12-14  | close  | 2        |

我如何才能 select 在一个查询中只对每个 issue_id 的最后一行进行操作 == 关闭?

SELECT action, issue_id
FROM table
WHERE action = 'close'
AND ???

仅对这三列进行聚合就足够了:

select issue_id, max(date) as date
from mytable 
where action = 'close'
group by issue_id

如果您需要显示更多列,请使用 distinct on:

select distinct on (issue_id) t.*
from mytable t
where action = 'close'
order by issue_id, date desc

您可以使用 distinct on :

select distinct on (issue_id) t.*
from table t
where action = 'close'
order by issue_id, date desc;

... columns might be null.

所以一定要使用DESC NULLS LAST以避免意外的结果:

SELECT DISTINCT ON (issue_id) *
FROM   tbl
WHERE  action = 'close'
ORDER  BY issue_id, date DESC NULLS LAST;

并且您可能希望将另一个独特的表达式(如 tbl_id)附加到 ORDER BY 列表,以打破相等日期之间的联系(如果可能的话)。否则你会得到一个可以随每次执行而改变的任意选择。

参见:

  • Select first row in each GROUP BY group?
  • Sort by column ASC, but NULL values first?