For one of our code, left join is not behaving properly in snowflake. Require your help if you can find solution around the same.
We have a sample data setup like mentioned below with basicc table join.
CREATE TABLE patient_test(pid INT);
INSERT INTO patient_test (pid) VALUES (100);
CREATE TABLE pateint_entry_test (pid INT,DateAdded DATETIME);
INSERT INTO pateint_entry_test (pid, DateAdded) VALUES (100, '2020-07-13');
Now look below code where I am just giveing you sample sub query that we are using with other query set. Where our motivation was to get date entry for each patient based on given start/end date.
WITh patient_cte AS(
SELECT * FROM patient_test
)
,
dates AS(
SELECT DATEDIFF(day, CONVERT_TIMEZONE('EST', 'UTC', CAST(TO_TIMESTAMP('2020-07-06') AS TIMESTAMP_NTZ)),
CONVERT_TIMEZONE('EST', 'UTC', CAST(TO_TIMESTAMP('2020-07-12') AS TIMESTAMP_NTZ))) AS Total_Days,
CONVERT_TIMEZONE('EST', 'UTC', CAST(TO_TIMESTAMP('2020-07-06') AS TIMESTAMP_NTZ)) AS Start_Date,
CONVERT_TIMEZONE('EST', 'UTC', CAST(TO_TIMESTAMP('2020-07-12') AS TIMESTAMP_NTZ)) AS end_date
)
,
cte2 (date) as (
SELECT TO_DATE(START_DATE) FROM dates
UNION ALL
SELECT TO_DATE(DATEADD(day, 1, date)) FROM cte2 WHERE date < (SELECT TOP 1 END_DATE FROM dates)
),
cte3 AS (
select * from patient_cte
cross join cte2
)
SELECT cte3.pid as p_pid,
pateint_entry_test.pid as p_entry_pid,
pateint_entry_test.DateAdded,
cte3."DATE" ,
IFNULL( pateint_entry_test.DateAdded, cte3."DATE") AS CALCULATEDDATEMEASURED
FROM cte3
LEFT JOIN pateint_entry_test ON
cte3.pid = pateint_entry_test.pid AND
cte3."DATE" = TO_DATE(pateint_entry_test.DateAdded)
Output of the query gives result as below.
Where you can see CALCULATEDDATEMEASURED
for Row number 2 to 7 are coming as 2020-07-06 00:00:00
. But as DAETADDED
is coming for null then it should come proper date based on DATE
column value ( Based on this condition IFNULL( pateint_entry_test.DateAdded, cte3."DATE")
)
Expecting below output from the query
Not sure what is wrong, but its not behaving as expected. Aprreciate your help on this. Thank you.
IFNULL()
rather than the standardCOALESCE()
. I doubt that makes a difference to your results, however. – Gordon Linoffcoalesce()
earlier but it was behaving same way. – rajusem(SELECT TOP 1 END_DATE FROM dates)
This is difficult to reproduce or help debug with example data for the tables that you are referencing in your example code. – Mike Walton