【问题标题】:Removing duplicates in a SQL Query删除 SQL 查询中的重复项
【发布时间】:2019-12-11 11:16:18
【问题描述】:

我有很多表连接在一起进行查询,结果有几列。我将专注于支持我的两个特定列,客户和职位。

我需要为每个位置为 2、3、14 和 15 的客户引入数据。

但是,客户可以有多个职位,如果客户同时拥有 14 和 15 的职位,我需要过滤掉后面的数字

我尝试使用这篇文章中的逻辑: Using NOT IN with NOT EQUAL when querying

但是,当我使用此方法时,我收到一条错误消息,指出 Position 不在 group by 子句(或有)中。

select Customer, Position
from Customers

where Position in (2, 3, 14, 15)

我得到的结果当然是这样的:

Customer    Position

Rebecca     3
Jane        2
Charley     14
Charley     15
Adam        2
Adam        14
Frank       3
Frank       14
Frank       15
Joe         3
Joe         15

但我需要它们看起来像这样。基本上,当客户有 14 个时,我需要所有条目,而当列表中已经存在 14 时,我不需要位置 15 的条目。

Customer    Position

Rebecca     3
Jane        2
Charley     14
Adam        2
Adam        14
Frank       2
Frank       14
Joe         3
Joe         15

【问题讨论】:

  • 当客户有 14 个时我需要所有条目,当列表中已经存在 14 时我不需要位置 15 的条目 !!!你了解这种情况吗?
  • 用您正在使用的数据库标记您的问题。而且您的错误消息没有意义。该查询既没有 group by 也没有 having 子句。
  • 例如,如果我有这个:Frank 14 Frank 15 我只需要在我的输出中:Frank 14 但是,如果我只有这个:Joe 15 那么我需要那个单一的条目。如果客户的职位已经是 14,我不需要为每个客户“仅”输入 15 的条目。这不清楚吗?
  • 这个查询没有这些,没有。

标签: sql sql-server duplicates


【解决方案1】:

您可以使用窗口函数。像这样的:

select Customer, Position
from (select c.*,
             sum(case when position = 14 then 1 else 0 end) over (partition by customer) as has_14
      from Customers c
      where Position in (2, 3, 14, 15)
     ) c
where position <> 15 or has_14 = 0;

【讨论】:

    【解决方案2】:

    对于Position = 14 和Position = 15 存在的情况,您可以使用NOT EXISTS:

    select c.Customer, c.Position
    from Customers c
    where 
      c.Position in (2, 3, 14)
      or (
        c.Position = 15
        and
        not exists (
          select 1 from Customers
          where Customer = c.Customer and Position = 14
        )
      )
    

    查看演示。
    结果:

    > Customer | Position
    > :------- | -------:
    > Rebecca  |        3
    > Jane     |        2
    > Charley  |       14
    > Adam     |        2
    > Adam     |       14
    > Frank    |        3
    > Frank    |       14
    > Joe      |        3
    > Joe      |       15
    

    我猜Frank 在预期结果中你错误地拥有2 而不是3。

    【讨论】:

      【解决方案3】:

      这个解决方案应该适用于大多数 SQL 方言,即那些不支持窗口函数的方言。此外,它只使用不相关的子查询,这意味着子查询只对整个查询执行一次,而不是对 Position = 15 的每一行执行一次:

      select Customer, Position
      from Customers
      where 
        Position in (2, 3, 14)
        or (
          Position = 15
          and
          Customer not in (
            select Customer from Customers where Position = 14
          )
        );
      

      【讨论】:

        猜你喜欢
        • 2014-07-03
        • 2023-03-17
        • 1970-01-01
        • 2015-08-12
        • 2012-11-02
        • 2021-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多