【问题标题】:Select distinct + select top to merge multiple rows选择 distinct + 选择顶部以合并多行
【发布时间】:2009-12-11 18:36:10
【问题描述】:

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

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

【问题讨论】:

  • 什么数据库?查询看起来正确 - 请显示一些数据和预期结果。

标签: sql sql-server filter unique distinct


【解决方案1】:

你的错误是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

【讨论】:

    【解决方案2】:

    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
    

    【讨论】:

      猜你喜欢
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      • 2013-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多