【问题标题】:Get max of two dates from two different tables in teradata - scenario?从 teradata 中的两个不同表中获取最多两个日期 - 场景?
【发布时间】:2010-12-27 04:27:18
【问题描述】:

我有两个表 table1 和 table2。表 2 的行数少于表 1。在这两个表中,table1 中有两个日期列 caldate1,table2 中有两个日期列 caldate2。所以现在我需要加入这两个表并获得两个日期列的最大值并将其保存在新表中。但是,如果我们在这两个表上进行内部连接,则 table2 中不存在的 table1 行将不会进入最终表。所以我们需要一些类似

的东西
table1 
left outer join
table2

但是有一种情况是两个日期都为空。那么我可以在以下情况下使用合并来获取正确的数据吗..

1。 table1 中的行在 table2 中不存在 -> 那么 table1 中的 caldate1 应该进入决赛桌。

2。 table1 中的行在 table2 中,table1 的 caldate1 和 table2 的 caldate2 为空 -> 然后 null 应该进入最终表的日期列

3。 table1 中的行在 table2 中,caldate1 不为空,caldate2 为空 -> 然后 caldate1 应该进入决赛桌。

4。 table1 中的行在 table2 中并且 caldate1 为空且 caldate2 不为空 -> 然后 caldate2 应该进入最终表

5。 table1 中的行在 table2 中并且 caldate1 大于 caldate2 -> caldate1 应该进入最终表

6。 table1 中的行在 table2 中并且 caldate2 大于 caldate1 -> caldate2 应该进入最终表

我们不需要考虑 table2 中与 table1 不匹配的行。所以基本上我需要所有 table1 行,如果两个表中都有特定的行,则最新的 caldate。提前致谢。我无法获得正确的功能来执行此操作。它会合并吗?

【问题讨论】:

  • 你得到的看起来是正确的。你有什么问题?
  • 是的,我在提出问题后想通了。所以我为用户粘贴了答案。任何人都可以请关闭这个。谢谢。
  • 回答您自己的问题,然后将其标记为正确答案。

标签: left-join max teradata coalesce


【解决方案1】:

从上面的查询中,如果 table2 中存在某个数字,而 table1 中没有,这些记录将被删除,您可以在上面的查询中使用完全外连接。

或请参阅下面的查询也将涵盖该场景。

sel number,max(date1) from (
  sel number,max(caldate1) as date1
    from table1
  union
  sel number,max(caldate2) as date1
    from table2
)tmp ;

【讨论】:

    【解决方案2】:

    我正在考虑做如下的事情来满足我的要求。

    SELECT 
    a.number,
    CASE WHEN ZEROIFNULL(a.caldate1) > ZEROIFNULL(b.caldate2)
    THEN a.caldate1  -- This is working
    ELSE
    b.caldate2
    END AS caldate
    /*COALESCE (a.caldate1,caldate2) AS caldate*/ -- This is not giving max of dates
    FROM 
    table1  a
    LEFT OUTER JOIN
    table2  b
    ON
    a.number = b.number
    

    感谢您的帮助。现在它通过上述方法完成。

    【讨论】:

      猜你喜欢
      • 2011-10-31
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      • 2020-07-19
      • 2019-09-13
      • 2021-08-10
      相关资源
      最近更新 更多