【问题标题】:SQL query to pick the IDs according to below details根据以下详细信息选择 ID 的 SQL 查询
【发布时间】:2021-11-25 18:06:25
【问题描述】:

当条件1为13且条件2为14时,我需要确定数据中的最后一个事件。但是,它不应该选择那些已经通过条件1为15和条件2为16的ID,然后最后一个事件是13和 14. 即,在下面的数据中,它不应该选择 ids 102 和 103。

数据如下

id   datetime       date           condition1   condition2
101 01-08-2021 13:00:41 01-08-2021    11          12    
101 06-08-2021 08:08:21 05-08-2021    13          14    
101 07-08-2021 21:05:32 07-08-2021    15          16
102 05-08-2021 14:08:32 05-08-2021    11          12
102 08-08-2021 06:13:13 08-08-2021    13          14
102 10-08-2021 13:09:55 10-08-2021    15          16
102 11-08-2021 18:00:00 11-08-2021    13          14
103 26-08-2021 14:04:22 26-08-2021    11          12    
103 28-08-2021 12:09:08 28-08-2021    13          14
103 31-08-2021 17:45:00 31-08-2021    15          16
103 02-09-2021 07:00:04 02-09-2021    17          18
103 05-09-2021 09:00:04 05-09-2021    13          14
104 21-08-2021 11:11:12 21-08-2021    11          12    
104 25-08-2021 10:09:35 25-08-2021    13          14
104 31-08-2021 08:35:40 31-08-2021    15          16
105 23-08-2021 09:05:54 23-08-2021    11          12
105 24-08-2021 10:00:22 24-08-2021    13          14

预期输出

id      datetime           date       condition1   condition2
105 04-09-2021 10:00:22 24-08-2021        13          14

【问题讨论】:

    标签: datetime teradata teradatasql


    【解决方案1】:

    我会使用子查询来排除具有condition1 = 15condition2 = 16 的ID

    SELECT * FROM mytable
    WHERE 
        condition1 = 13 
        AND condition2 = 14
        AND id NOT IN (
            SELECT id FROM mytable WHERE condition1 = 15 AND condition2 = 16
        )
    ORDER BY datetime DESC
    LIMIT 1;
    

    【讨论】:

      【解决方案2】:
      select *
      from vt
      qualify row_number()     -- last event in the data 
              over (partition by id
                    order by datetime desc) = 1
          and condition1 = 13  -- when condition1 is 13 
          and condition2 = 14  -- and condition2 is 14
      
          -- not pick those IDs which have already passed through condition1 as 15 and condition2 as 16
          and count(case when condition1 = 15 and condition2 = 16 then 1 end)
              over (partition by id) = 0
      ;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-15
        • 2014-05-25
        • 1970-01-01
        • 2019-02-21
        相关资源
        最近更新 更多