sql分区的多级条件

dauxcl2d  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(298)

我必须从另一个来源填充teradata表,可以简化为:

+------+------+------------+------------+
| Col1 | Col2 |    Col3    |    Col4    |
+------+------+------------+------------+
| 1234 |    0 | 01/01/2009 | 01/04/2019 |
| 1234 |    3 | 01/01/2010 | 01/05/2020 |
| 2345 |    1 | 20/02/2013 | 01/04/2019 |
| 2345 |    0 | 20/02/2013 | 01/04/2018 |
| 2345 |    2 | 31/01/2009 | 01/04/2017 |
| 3456 |    0 | 01/01/2009 | 01/04/2019 |
| 3456 |    1 | 01/01/2015 | 01/04/2019 |
| 3456 |    1 | 01/01/2015 | 01/05/2017 |
| 3456 |    3 | 01/01/2015 | 01/04/2019 |
+------+------+------------+------------+

col1在source中是重复的,因此我们有规则为col1中的if值选择正确的行(col1在最终结果中是唯一的):
如果值重复,则选择col3中的最近日期
如果(且仅当)它仍然是重复的,则选择col2=1的行
如果仍然重复,则选择col4中的最近日期。
考虑到上表,我们应该得到以下结果:

+------+------+------------+------------+
| Col1 | Col2 |    Col3    |    Col4    |
+------+------+------------+------------+
| 1234 |    3 | 01/01/2010 | 01/05/2020 |
| 2345 |    1 | 20/02/2013 | 01/04/2019 |
| 3456 |    1 | 01/01/2015 | 01/04/2019 |
+------+------+------------+------------+

我开始使用partition by对第3列中出现的每个值进行分组,但是我不知道如何在sql查询中应用每个partition的条件
谢谢你的帮助

sy5wg1nm

sy5wg1nm1#

你可以用 QUALIFY 在teradata中简化语法:

SELECT col1, col2, col3, col4
FROM mytable
QUALIFY ROW_NUMBER() OVER(
  PARTITION BY col1 -- Group rows by "col1" values
  ORDER BY col3 DESC, CASE WHEN col2 = 1 THEN 1 ELSE 2 END, col4 DESC -- Order rows
) = 1 -- Get "first" row in each group

否则,与上述答案相同。

a1o7rhls

a1o7rhls2#

你可以用 row_number() :

select t.*
from (select t.*,
             row_number() over (partition by col1
                                order by col3 desc,
                                         (case when col2 = 1 then 1 else 2 end),
                                         col4 desc
                               ) as seqnum
      from t
     ) t
where seqnum = 1;

相关问题