我有两个表table1和table2。表2的行数少于table1。在这两个表中,table1中有两个日期列caldate1,table2中有两个日期列caldate2。所以现在我需要加入这两个表并获取两个日期列的最大值并将其保留在新表中。但是如果我们内部连接这两个表,则table2中不存在的table1行将不会进入最终表。所以我们需要一些像
这样的东西table1
left outer join
table2
但是有一种情况是两个日期都有空。那么我可以使用coalesce在下面的场景中获取正确的数据。
1。 table1中的行不在table2中 - >然后table1中的caldate1应该进入决赛桌。
2。 table1中的行在table2中,table1的caldate1和table2的caldate2是nulls - >那么null应该进入最终表的日期列
3。 table1中的行在table2中,caldate1不为null,caldate2为null - >然后caldate1应该进入决赛桌。
4。 table1中的行在table2中,caldate1为null,caldate2不为null - >然后caldate2应该进入决赛桌
5。 table1中的行在table2中,caldate1大于caldate2 - > caldate1应该进入决赛桌
6。 table1中的行在table2中,caldate2大于caldate1 - > caldate2应该进入决赛桌
我们不需要考虑table2中与table1不匹配的行。所以基本上我需要所有table1行和最新的caldate,如果两个表中都有特定的行。提前致谢。我无法得到正确的功能。它合并了吗?
答案 0 :(得分: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 ;
答案 1 :(得分:0)
我正在考虑做下面的事情以满足我的要求。
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
感谢您的帮助。现在通过上述方法完成。