选择distinct + select top以合并多行

时间:2009-12-11 18:36:11

标签: sql sql-server filter unique distinct

我正在尝试从表中选择行,每个电子邮件地址一行,并从电子邮件列表的顶行返回一个名字。但是,查询会返回多个电子邮件地址。我做错了什么?

SELECT 
    DISTINCT email,
    (SELECT TOP 1 firstname 
     FROM onsite_clients_archive oc 
     WHERE oc.client_id=oca.client_id 
     ORDER BY client_id)
FROM onsite_clients_archive oca 
WHERE users_user_id IS NULL

2 个答案:

答案 0 :(得分:3)

您的错误WHERE oc.client_id = oca.client_id应为WHERE oc.email = oca.email

你没有说你正在使用哪个DBMS,但如果它是MS SQL,以下也会做你想要的。

SELECT email, firstname
FROM (
    SELECT 
        email, firstname, 
        ROW_NUMBER() OVER (PARTITION BY email ORDER BY client_id DESC) AS intRow
    FROM onsite_clients_archive
    WHERE users_user_id IS NULL
) AS T
WHERE intRow = 1

答案 1 :(得分:0)

DISTINCT将应用于列列表中的所有列,因此在这种情况下,如果Onsite_Clients_Archive中有多个行具有相同的电子邮件地址,那么只要它们具有不同的名称,您将从查询中获取这些行。

考虑一下你要做什么......你想要每个不同的(不一定意味着这里的SQL关键字)电子邮件地址的第一个名称匹配它(首先按client_id的顺序定义)。如果没有看到实际的数据模型,我很难明确地说出来,但这是我的第一个猜测:

SELECT
     T1.email,
     T1.first_name
FROM
     Onsite_Clients_Archive T1
LEFT OUTER JOIN Onsite_Clients_Archive T2 ON
     T2.email = T1.email AND
     T2.client_id < T1.client_id
WHERE
     T2.client_id IS NULL   -- Assuming that this is a not null column, the only way it could be NULL is if there was no match