我有一个 SQL 表,需要检查两个日期中的最新日期,创建一个新列。可能有也可能没有这两个值,在这种情况下它默认为一个。
我有一个这样的生产案例:
+----------+----------+-----------+
| device | activity | date |
+----------+----------+-----------+
| device 1 | stage | 3/20/2018 |
| device 1 | test | 3/30/2018 |
| device 2 | stage | 6/1/2018 |
| device 2 | test | [null] |
+----------+----------+-----------+
我需要得到这个:
+----------+-----------------+
| device | stage_test_date |
+----------+-----------------+
| device 1 | 3/30/2018 |
| device 2 | 6/1/2018 |
+----------+-----------------+
我正在尝试这样:
case
when activity in ('stage', 'test')
then (select max(date))
else null
end as stage_test_date,
但我收到“不支持给定的相关子查询”错误。这是 PrestoDB,它使用 ANSI SQL。它适用于“然后(选择日期)”,但这并没有给我两个日期中最大的一个。
非常感谢您的建议!
最佳答案
为什么不这样做呢?
select device, max(date)
from t
group by device;
如果你想限制事件,或者添加一个where
:
select device, max(date)
from t
where activity in ('stage', 'test')
group by device;
关于sql - 如何获取 SQL case 语句中两个日期中的最新日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51616729/