I have these two tablesCREATE TABLE #TestData_1( PATID varchar(10) NULL, EpisodeNumber int NULL, DiagnosisType varchar(10) NULL)INSERT INTO #TestData_1 (PATID,EpisodeNumber)SELECT '1018', 26 UNION ALLSELECT '32181', 4 UNION ALLSELECT '32181', 4 UNION ALLSELECT '32181', 4 UNION ALLSELECT '32181', 4 UNION ALLSELECT '43497', 1 UNION ALLSELECT '603', 38 UNION ALLSELECT '603', 49CREATE TABLE #TestData_2( PATID varchar(10) NULL, EpisodeNumber int NULL)INSERT INTO #TestData_2SELECT '603', 38 UNION ALLSELECT '603', 38 UNION ALLSELECT '603', 39 UNION ALLSELECT '603', 40 UNION ALLSELECT '603', 41 UNION ALLSELECT '603', 3 UNION ALLSELECT '43497', 1 UNION ALLSELECT '1018', 27 UNION ALLSELECT '1018', 29 UNION ALLSELECT '1018', 30 UNION ALLSELECT '1018', 31
I want to update the column DiagnosisType in #TestData_1 using the following rule:If at least record exists in #TestData_2 for a given PATID/EpisodeNumber then DiagnosisType = 'U' Else DiagnosisType = 'A'End if
So I have come up with this query to find the correct diagnosisType:SELECT d.patid, d.episodeNumber, case when h.patid is not null then 'U' else 'A' end as diagnosisType FROM #TestData_1 d left join (select distinct x.patid, x.episodeNumber from #TestData_2 x) h on d.patid = h.patid and d.EpisodeNumber = h.EpisodeNumber
That gets me this output:patid episodeNumber diagnosisType===== ============= =============1018 26 A32181 4 A32181 4 A32181 4 A32181 4 A43497 1 U603 38 U603 49 A
Which is the correct output.But how do I wrap it in an Update Statement?I tried this:update #TestData_1 set DiagnosisType = y.diagnosisType from (SELECT case when h.patid is not null then 'U' else 'A' end as diagnosisType FROM #TestData_1 d left join (select distinct x.patid, x.episodeNumber from #TestData_2 x) h on d.patid = h.patid and d.EpisodeNumber = h.EpisodeNumber) y
But this gives me this output:patid episodeNumber diagnosisType===== ============= =============1018 26 A32181 4 A32181 4 A32181 4 A32181 4 A43497 1 A603 38 A603 49 A
Which is wrong. The values in red should be U not A.Thanks,Laurie