【问题标题】:Select all rows with smallest date [closed]选择日期最小的所有行[关闭]
【发布时间】:2018-06-13 19:56:43
【问题描述】:

我需要有关 SQL 查询的帮助。从 my_wl​​_table 中,我需要选择所有行,但以下条件除外:如果 session_id 出现多次(例如,s1),我需要为此会话 ID 选择 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),不应包含在输出结果中。

【问题讨论】:

  • 你能和我们分享你的代码尝试吗?你写了什么没有产生正确的输出?

标签: sql amazon-redshift


【解决方案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

【讨论】:

【解决方案2】:

这似乎可行。

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}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多