I'm new to CTEs in Transact SQl and I need help optimizing very slow performance joining the results of two CTEs together.
The first CTE is a number of encounters that returns 147 rows in 2 seconds. The second CTE is progress notes for all those encounters returning 136 rows in 18 seconds.
When I try to left outer join progress notes to encounters, it runs very slowly. I can't even get any data back after 3 minutes! Both datasets are ordered by the field they join on (the field that they join on is not unique in the progress notes CTE)
; with E as (Thanks in advance for any troubleshooting suggestions!
SELECT DISTINCT TOP 100 PERCENT
...............................
ORDER BY PAT_ENC_CSN_ID
) ,
PROGRESS_NOTES AS (
SELECT DISTINCT TOP 100 PERCENT
...............................
ORDER BY PAT_ENC_CSN_ID
)SELECT * FROM E LEFT OUTER JOIN PROGRESS_NOTES ON E.PAT_ENC_CSN_ID = PROGRESS_NOTES.PAT_ENC_CSN_ID
To err is human, to REALLY foul things up requires a computer