Today I ran into an interesting SQL problem, and while I came up with a solution that works, I doubt that this is the best or most efficient answer. I belong to the experts here - help me learn something and improve my query! RDBMS is SQL Server 2008 R2, the query is part of an SSRS report that will run against about 100,000 rows.
Essentially, I have a list of identifiers that can have multiple values associated with them, the values are Yes, No, or some other string. For ID x, if any of the values is Yes, x should be Yes, if all of them are No, it should be No, if they contain any other values, but yes and no, display this value. I only want to return 1 row to ID, without duplicates.
Simplified version and test case:
DECLARE @tempTable table ( ID int, Val varchar(1) ) INSERT INTO @tempTable ( ID, Val ) VALUES ( 10, 'Y') INSERT INTO @tempTable ( ID, Val ) VALUES ( 11, 'N') INSERT INTO @tempTable ( ID, Val ) VALUES ( 11, 'N') INSERT INTO @tempTable ( ID, Val ) VALUES ( 12, 'Y') INSERT INTO @tempTable ( ID, Val ) VALUES ( 12, 'Y') INSERT INTO @tempTable ( ID, Val ) VALUES ( 12, 'Y') INSERT INTO @tempTable ( ID, Val ) VALUES ( 13, 'N') INSERT INTO @tempTable ( ID, Val ) VALUES ( 14, 'Y') INSERT INTO @tempTable ( ID, Val ) VALUES ( 14, 'N') INSERT INTO @tempTable ( ID, Val ) VALUES ( 15, 'Y') INSERT INTO @tempTable ( ID, Val ) VALUES ( 16, 'Y') INSERT INTO @tempTable ( ID, Val ) VALUES ( 17, 'F') INSERT INTO @tempTable ( ID, Val ) VALUES ( 18, 'P') SELECT DISTINCT t.ID, COALESCE(t2.Val, t3.Val, t4.Val) FROM @tempTable t LEFT JOIN ( SELECT ID, Val FROM @tempTable WHERE Val = 'Y' ) t2 ON t.ID = t2.ID LEFT JOIN ( SELECT ID, Val FROM @tempTable WHERE Val = 'N' ) t3 ON t.ID = t3.ID LEFT JOIN ( SELECT ID, Val FROM @tempTable WHERE Val <> 'Y' AND Val <> 'N' ) t4 ON t.ID = t4.ID
Thanks in advance.