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

Posted

技术标签:

【中文标题】如何排除具有相似列的行?【英文标题】: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 不,它们可能为空 【参考方案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 列表以打破相等日期之间的联系。否则,您会得到一个随每次执行而变化的任意选择。

见:

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

【讨论】:

以上是关于如何排除具有相似列的行?的主要内容,如果未能解决你的问题,请参考以下文章

排除具有数字字符的行,仅在行的开头

排除具有多对多关系的行

%in% 的对面:排除具有向量中指定值的行

使用 awk 排除以多个字段为条件的行

在排除某些行的矩阵的列中查找最大元素

TSQL - 排除与临时表匹配的行