选择日期最小的所有行

时间:2018-06-13 19:56:44

标签: sql amazon-redshift

我需要SQL查询的帮助。从 my_wl​​_table ,我需要选择所有行,但以下情况除外:如果 session_id 多次出现(例如, s1 ),我需要为此会话ID选择raw,其中 first_trigger_hit_datetime 列最低:

my_wl​​_table:

**session_id  |  first_trigger_hit_datetime  |  column1**  
s1            |         2018-06-04           |  T          
s2            |         2018-06-06           |  C     
s3            |         2018-06-02           |  T     
s1            |         2018-06-09           |  T     

我需要的输出

s1            |         2018-06-04           |  T          
s2            |         2018-06-06           |  C     
s3            |         2018-06-02           |  T   

因此,对于具有多个条目的会话,我只需要选择一个日期时间值最小的行。最后一行(2018-06-09 datetime)不应包含在输出结果中。

2 个答案:

答案 0 :(得分:1)

一种方法使用first_value()

select distinct session_id,
       min(first_trigger_hit_datetime) over (partition by session_id) as first_trigger_hit_datetime,
       first_value() over (partition by session_id order by first_trigger_hit_datetime desc) as column1
from t;

因为它仅作为分析函数提供,所以您需要select distinct

答案 1 :(得分:1)

这似乎可行。

select session_id,
       first_trigger_hit_datetime,
       column1
  from (select t.*,
               row_number() over 
                 ( partition by session_id
                       order by first_trigger_hit_datetime
                 ) as rn 
          from t
       ) tmp
 where rn = 1;

可替换地:

SELECT * 
  FROM t
 ORDER
    BY row_number() over 
         ( partition by session_id
               order by first_trigger_hit_datetime
         ) as rn
FETCH FIRST 1 ROWS WITH TIES; -- Double check this does what you want in case of a tie on {session_id, first_trigger_hit_datetime}