I have the following query that returns a comma separated list of email ids for the selected user.
CREATE TABLE TEST
(
ID INT PRIMARY KEY,
FIRSTNAME VARCHAR(30) NOT NULL,
LASTNAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(50)
)
INSERT INTO TEST VALUES (1, 'Tom', 'Lew', 'tom@hotmail.com')
INSERT INTO TEST VALUES (2, 'Tom', 'Lew', 'tom@hotmail.com')
INSERT INTO TEST VALUES (3, 'Jack', 'Stan', 'jstan@hotmail.com')
INSERT INTO TEST VALUES (4, 'Tom', 'Reed', 'tomreed@hotmail.com')
INSERT INTO TEST VALUES (5, 'Tom', 'Reed', 'tomr@hotmail.com')
INSERT INTO TEST VALUES (6, 'Tom', 'Reed', 'treed@hotmail.com')
DECLARE @result VARCHAR(MAX)
SELECT @result = COALESCE(@result + ',', '') + [EMAIL]
FROM [TEST]
WHERE [FirstName] = 'Tom' AND [LastName] = 'Reed'
SELECT @result
I need to modify the query so that it returns only one value either
– one email Id if there is only one email id associated with ‘Tom Reed’
– string ‘multiple’ if more than one email ids found for ‘Tom Reed’
I somehow was able to get the desired result but not sure about the performance. In real scenario this table will have thousands of records and will be joined to other tables.
SELECT
DISTINCT
CASE
WHEN CNT = 1 THEN EMAIL
ELSE 'MULTIPLE'
END
FROM (SELECT
ID, EMAIL,
COUNT(*) OVER() CNT
FROM TEST
WHERE [FirstName] = 'Tom' AND [LastName] = 'Reed') T
Sorry, if the subject line and the content doesn’t match. Was not sure about the description.
Desired Results:
-
If queried on ‘Tom Reed’
Output: Multiple -
If queried on ‘Tom Lew’
Output: Multiple -
If queried on ‘Jack Stan’
Output: jstan@hotmail.com
I think this would work (untested):
And if you need just the word by the passed in params:
This should return either the Email or the word Multiple.