首页 > 解决方案 > postgres sql查找具有状态和日期序列的记录

问题描述

用户表

id createdDate status
1  2021-03-10  Active
1  2021-03-05  Pending
1  2021-03-07  Failed
2  2020-09-20  Pending
2  2020-09-01  Active
2  2020-07-01  Failed

寻找选择 sql 来获取具有活动状态的记录的 ID

  1. 所有三个活动、失败待定状态或
  2. 活动和失败状态或
  3. 活动和待定状态

Active 是最新的(createdDate)。

从上面的例子我需要的结果

1  2021-03-10  Active

标签: sqlpostgresql

解决方案


您可以按 id 分组并在HAVING子句中设置条件:

SELECT id, MAX(createdDate) createdDate, 'Active' status
FROM tablename
WHERE status IN ('Active', 'Failed', 'Pending')
GROUP BY id
HAVING MAX(createdDate) = MAX(CASE WHEN status = 'Active' THEN createdDate END) -- the last date is the date with 'Active' status
   AND COUNT(DISTINCT status) >= 2 -- at least 2 statuses exist

如果“活动”、“失败”和“待定”是列的唯一可能值,status您可以删除该WHERE子句。

演示


推荐阅读