开发者

Get max of two dates from two different tables in teradata - scenario?

开发者 https://www.devze.com 2022-12-14 07:48 出处:网络
I have two tables table1 and table2. Table2 is having less number of rows than table1. In these two tables there are two date columns caldate1 in table1 and caldate2 in table2. So now I need to join o

I have two tables table1 and table2. Table2 is having less number of rows than table1. In these two tables there are two date columns caldate1 in table1 and caldate2 in table2. So now I need to join on these two tables and get the maximum of the two date columns and keep that in new table. But if we inner join on these two tables the table1 rows which are not there in table2 will not go into the final table. So we need some thing like

table1 
left outer join
table2

But there is a situation that the two dates are having nulls. So Can I use coalesce to get the correct data in the below scenarios..

1. row in table1 is not there in table2 -> then the caldate1 in table1 should go into final table.

2. row in table1 is there in table2 and the caldate1 of table1 and caldate2 of table2 are nulls -> then null should come into final table's date column

3. row in table1 is there in table2 and caldate1 is not null and caldate2 is null开发者_运维技巧 -> then caldate1 should come into final table.

4. row in table1 is there in table2 and caldate1 is null and caldate2 is not null -> then caldate2 should come into final table

5. row in table1 is there in table2 and caldate1 is greater than caldate2 -> caldate1 should come into final table

6. row in table1 is there in table2 and caldate2 is greater than caldate1 -> caldate2 should come into final table

We dont need to consider the rows in table2 which are not matching with table1. So basically i need all table1 rows with latest of the caldate if a particular row is there in both tables. Thanks in advance. I am not able to get correct function to do it.Is it coalesce?


From the above query, if some number present in table2 and not in table1, those records will be dropped, You can use full outer join in the above query.

OR See the below query will cover that scenario also.

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


I am thinking of doing something like below to satisfy my requirement.

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

Thanks for helping. Now its done by the above method.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号