sql - 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
- 所有三个活动、失败和待定状态或
- 活动和失败状态或
- 活动和待定状态
Active 是最新的(createdDate)。
从上面的例子我需要的结果
1 2021-03-10 Active
解决方案
您可以按 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
子句。
见演示。
推荐阅读
- reactjs - 如何使用 Redux 在 React Native 中使用线程调用 API?
- postgresql - ActiveRecord Rails 4,如何查看数组属性是否包含数组中的任何值
- css - 圆角缩略图中的黑边(Emporio 主题)?
- powershell - 以编程方式将 azure blob 挂载为网络驱动器
- ios - 将 Xcode 存档移动到另一台计算机
- php - 如何在 PHP Laravel 中编写类似的代码?
- python - 用 voila 在 jupyter 中绘制 pandas 数据框
- javascript - 在 lodash 中使用 _.groupBy 将字符串聚合到数组中
- javascript - 自定义组件的清除状态
- python - 如何在 python 中从 FTP 将 CSV 文件读入数据帧