HiA while back I posted this topic: Update statement syntax ... and got a great answer (thanks Lamprey). Well now I need to add an additional twist to the problem.I have added a column (StartDate) to the #TestData_1 table. So now I have the following two tables:CREATE TABLE #TestData_1( PATID varchar(10) NULL, EpisodeNumber int NULL, StartDate datetime Null, DiagnosisType varchar(10) NULL)INSERT INTO #TestData_1 (PATID,EpisodeNumber,StartDate)SELECT '1018', 26, '2010-01-01' UNION ALLSELECT '32181', 4, '2010-04-01' UNION ALLSELECT '32181', 4, '2011-02-01' UNION ALLSELECT '32181', 4, '2010-03-22' UNION ALLSELECT '32181', 4, '2011-01-01' UNION ALLSELECT '43497', 1, '2010-01-01' UNION ALLSELECT '603', 38, '2010-01-01' UNION ALLSELECT '603', 49, '2011-02-15'CREATE 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
My original requirement was:If at least one record exists in #TestData_2 for a given PATID/EpisodeNumber then DiagnosisType = 'U' Else DiagnosisType = 'A'End if
My new requirement (the twist) is: If more than one record exists in #TestData_1 for a given PATID/EpisodeNumber (and does not exist in #TestData_2) then only the earliest dated one should have a Diagnosis Type of 'A' all the rest (in the given PATID/EpisodeNumber) should have a Diagnosis Type of 'U'. This changes my expected output to this:PATID EpisodeNumber StartDate DiagnosisType---------- ------------- ------------------------1018 26 2010-01-01 A32181 4 2010-04-01 U32181 4 2011-02-01 U32181 4 2010-03-22 A32181 4 2011-01-01 U43497 1 2010-01-01 U603 38 2010-01-01 U603 49 2011-02-15 A
(Red donates change from original expected results).Right now I am thinking in terms of running two update statements. The first one from the original problem and then one that somehow finds all the rows (in TestData_1) where there are two or more rows for a given PATID/EpisodeNumber where DiagnosisType is set to 'A' for all rows and update all but the minimum StartDate row to 'U'.There are two issues with this solution:- I am not sure how to do that (though I am working on it).
- It might not be the most efficient way to do this.
Any help would be much appreciated. Thanks,Laurie