SQL 查询以选择具有条件的最后一个条目

SQL query to pick the last entry with a condition

我正在尝试查询数据,我需要在其中选择最后一个事件在条件 1 中为 3,在条件 2 中为 4 并且最后一个事件应在一月份内的数据。

数据如下,

col1    condition1  condition2  date
1234    0              1        01/01/2020  
1234    1              2        02/01/2020  
1234    2              3        04/01/2020  
1234    3              4        10/01/2020  
5678    0              1        25/01/2020  
5678    1              2        26/01/2020  
5678    2              3        28/01/2020  
5678    3              4        03/02/2020  
8901    0              1        17/01/2020  
8901    1              2        18/01/2020  
8901    2              3        20/01/2020  
8901    3              4        22/01/2020  
8901    4              5        24/01/2020  
8901    5              6        26/01/2020  
3467    0              1        13/01/2020  
3467    1              2        15/01/2020  
3467    2              3        16/01/2020  
3467    3              4        24/01/2020  
3467    4              5        27/01/2020  
3467    5              6        28/01/2020  

预期输出

col1    condition1  condition2  date
1234    3              4        10/01/2020

翻译“...选择带有条件的最后一个条目 [...] 其最后一个事件在条件 1 中为 3,在条件 2 中为 4,并且最后一个事件应在一月份内。" to SQL:

SELECT col1, condition1, condition2, "date"
FROM tablename AS t1
WHERE condition1 = 3 AND condition2 = 4
  AND EXTRACT(MONTH FROM "date") = 1
  AND NOT EXISTS (SELECT * FROM tablename AS t2
                  WHERE t2.col1 = t1.col1
                    AND t2."date" > t1."date")

顺便说一句,DATE 是 Teradata 保留字 (https://en.wikipedia.org/wiki/SQL_reserved_words)。如果您有一个具有该名称的列,则必须将其分隔为 "date".

编辑:抱歉,我忘了提到年份:(它应该提取 2020 年 1 月和 2020 年的数据。

SELECT col1, condition1, condition2, "date"
FROM tablename AS t1
WHERE condition1 = 3 AND condition2 = 4
  AND "date" BETWEEN DATE'2021-01-01' AND DATE'2021-01-31'
  AND NOT EXISTS (SELECT * FROM tablename AS t2
                  WHERE t2.col1 = t1.col1
                    AND t2."date" > t1."date")
select *
from mytable
qualify
   rank()
   over (partition by col1
         order by datecol desc) = 1 -- last event
-- additional conditions
and datecol between date '2021-01-01' and date '2021-01-31'
and condition1 = 3
and condition2 = 4;