With 2 tables, 1 a code table with names, and another with a nonunique id column, if there are more than 1 value for the code table, return the word Both, otherwise return the code value nameI'm looking to see if there's a better way than what I have come up withThe desired result set isParentID Name ----------- -------------------------------------------------- 1 Agencey 12 Agencey 23 Both(3 row(s) affected)
Here's the codeCREATE TABLE ACodes ([id] int IDENTITY(1,1), [Name] varchar(50))CREATE TABLE Capacity ([Parentid] int, ACodeID int)GOINSERT INTO ACodes ([Name])SELECT 'Agencey 1' UNION ALL SELECT 'Agencey 2'GOINSERT INTO Capacity (ParentID, ACodeID)SELECT 1, 1 UNION ALLSELECT 2, 2 UNION ALLSELECT 3, 1 UNION ALLSELECT 3, 2GOSELECT DISTINCT ParentID, 'Both' AS [Name] FROM CapacityWHERE ParentID in ( SELECT ParentID FROM Capacity c GROUP BY ParentID HAVING COUNT(*) > 1)UNION ALLSELECT ParentID, [Name]FROM Capacity c INNER JOIN ACodes a ON c.ACodeID = a.[ID]WHERE ParentID in ( SELECT ParentID FROM Capacity c GROUP BY ParentID HAVING COUNT(*) = 1)ORDER BY ParentIDGODROP TABLE ACodes, CapacityGO
Brett8-)Hint: Want your questions answered fast? Follow the direction in this linkhttp://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspxAdd yourself!http://www.frappr.com/sqlteam