【问题标题】:How to exclude rows with similar columns?如何排除具有相似列的行?
【发布时间】:2021-03-25 08:08:02
【问题描述】:

有一张桌子:

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

如何在一个查询中为每个 issue_id 只选择最后一行的 action == close?

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

【问题讨论】:

  • 所有列NOT NULL?
  • @ErwinBrandstetter 不,它们可能为空

标签: sql postgresql datetime greatest-n-per-group


【解决方案1】:

仅对于这三列,聚合就足够了:

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

【讨论】:

    【解决方案2】:

    你可以使用distinct on :

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

    【讨论】:

      【解决方案3】:

      ...列可能为空。

      所以请务必使用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 列表以打破相等日期之间的联系。否则,您会得到一个随每次执行而变化的任意选择。

      见:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-19
        • 2018-09-14
        • 1970-01-01
        • 2021-09-02
        相关资源
        最近更新 更多