SQL Server查询只返回一个值而不是返回多个值

时间:2013-01-16 19:29:27

标签: sql sql-server-2008

我有以下查询返回所选用户的逗号分隔的电子邮件ID列表。

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

我需要修改查询,以便它只返回一个值 - 如果只有一个与“Tom Reed”相关联的电子邮件ID,则会显示一封电子邮件ID - 如果为'Tom Reed'找到多个电子邮件ID,则为字符串'multiple'

我以某种方式能够获得理想的结果但不确定性能。在实际情况中,此表将包含数千条记录,并将连接到其他表。

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

很抱歉,如果主题行和内容不匹配。不确定描述。

期望的结果:

  1. 如果查询'Tom Reed'

    Output: Multiple
    
  2. 如果查询'Tom Lew'

    Output: Multiple
    
  3. 如果查询'杰克斯坦'

    Output: jstan@hotmail.com
    

1 个答案:

答案 0 :(得分:2)

我认为这可行(未经测试):

SELECT DISTINCT
    FirstName, 
    LastName,  
    CASE 
      WHEN COUNT(Email) OVER (PARTITION BY FirstName,LastName) = 1 
      THEN Email 
      ELSE 'Multiple' END
FROM Test

如果你只需要传递参数的单词:

SELECT DISTINCT
    CASE 
      WHEN COUNT(Email) OVER (PARTITION BY FirstName,LastName) = 1 
      THEN Email 
      ELSE 'Multiple' END
FROM Test
WHERE FirstName = 'Tom' 
   AND LastName = 'Reed'

这应该返回电子邮件或单词Multiple。