如何获得SQL case语句中两个日期的最新值?

时间:2018-07-31 15:15:04

标签: sql hadoop presto

我有一个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。它适用于“然后(选择日期)”,但这并不能给我两个日期中最大的一个。

非常感谢您的建议!

4 个答案:

答案 0 :(得分:1)

为什么不这样做呢?

select device, max(date)
from t
group by device;

或者如果您想限制活动,则添加where

select device, max(date)
from t
where activity in ('stage', 'test') 
group by device;

答案 1 :(得分:0)

您可以使用相关的subquery方法:

select t.*
from table t
where activity in ('stage', 'test') and
      date = (select max(t1.date) from table t1 where t1.device = t.device);

您还可以使用GROUP BY条款:

select device, max(date) as stage_test_date
from table t
where activity in ('stage', 'test')
group by device; 

答案 2 :(得分:0)

在子查询中使用解析max():

select
    case 
        when activity in ('stage', 'test') 
        then max_date 
    end as stage_test_date,
    ...
from
(
select t.*, 
       max(date) over () as max_date 
 from table t
) s
;

答案 3 :(得分:0)

您可以使用此

select device, max(date) as stage_test_date 
from production 
group by device
order by device asc