【问题标题】:Finding all duplicate rows with the given conditions查找具有给定条件的所有重复行
【发布时间】:2017-08-27 01:22:08
【问题描述】:

我有一个名为 Fruit 的表,它有两列 (id,cost),我想选择 id 和 cost,并找到所有重复行,其中成本相同但 id 不同。我该如何编写这个查询?

我写了这个查询

SELECT id,cost
From Fruit a
WHERE (SELECT COUNT(*)
       FROM Fruit b 
       WHERE a.cost = b.cost
) > 1

这可行,但只给我成本相同但 id 也可能相同的行,我只想要成本相同但 id 不同的结果

【问题讨论】:

  • 您是否尝试将a.id != b.id 添加到内部where 子句中?
  • Madhusudna 这是 sql 所以运算符不等于由 显示。你不能使用 !=.

标签: sql database oracle


【解决方案1】:

这是你需要的:

SELECT DISTINCT F1.*
FROM Fruit F1
INNER JOIN Fruit F2 ON F1.id <> F2.id AND F1.cost = F2.cost

如果您还想列出重复的 id-cost 对,只需删除 DISTINCT

【讨论】:

    【解决方案2】:

    您可以添加一个简单的条件,其中 id 不相等。

    SELECT id,cost From Fruit a WHERE (SELECT COUNT(*) FROM Fruit b WHERE a.cost = b.cost and a.id b.id ) > 1

    这里不等于的运算符。 希望对你有帮助:)

    【讨论】:

    • 我试过了,但在 where 子句中不起作用
    • 这不起作用。你实际上应该做&gt; 0。并且可以选择在主SELECT 中添加DISTINCT
    【解决方案3】:

    您可以选择所有成本重复的行,使用 group by 并且 ccount(*) >1

    为此获取所有匹配的行

      select a.id, a.cost
      from Fruit a
      where cost in ( select b.cost 
       from  fruit b
       group by b.cost 
       having count(*) > 1
      ) 
    

    为避免重复结果,您可以添加不同的

      select distinct a.id, a.cost
      from Fruit a
      where cost in ( select b.cost 
       from  fruit b
       group by b.cost 
       having count(*) > 1
      ) 
    

    【讨论】:

    • 如果 id 相同,那么我也会得到这些行,我不确定如何使用此语法选择相同的成本但不同的 id
    • 返回的结果具有重复的 id,这不是 @spyang302 需要的。
    【解决方案4】:

    您可以添加一个 id 不相等的简单条件。

    SELECT id,cost From Fruit a WHERE (SELECT COUNT(*) FROM Fruit b WHERE a.cost = b.cost and a.id b.id ) > 1

    这里是sql中不等于的运算符。

    【讨论】:

    • Prateek,您两次发布了相同的答案。
    【解决方案5】:

    这行得通。在 SQL Server 中运行它,因为 Oracle 在 Fiddle 上已损坏,但应该可以在任一系统上运行。

    MS SQL Server 2014 架构设置

    CREATE TABLE ab
        ([id] int, [cost] int)
    ;
    
    INSERT INTO ab
        ([id], [cost])
    VALUES
        (1, 5),
        (2, 5),
        (3, 15),
        (3, 15),
        (4, 24),
        (5, 68),
        (6, 13),
        (7, 3)
    ;
    

    查询 1

    with a1 as (
    SELECT id
    ,cost
    ,rank () over (partition by cost order by id) dup
    From ab
      )
    
      select * from a1 where dup > 1
    

    Results

    | id | cost | dup |
    |----|------|-----|
    |  2 |    5 |   2 |
    

    然后返回所有重复成本的值:

    with a1 as (
    SELECT id
    ,cost
    ,rank () over (partition by cost order by id) dup
    From ab
      )
    
    ,a2 as ( select * from a1 where dup > 1)
    
    select * from ab
    join a2 on ab.cost = a2.cost
    

    【讨论】:

    • spyang302 需要获取 1-5 和 2-5,而不是 3-15,这两个记录中的 id 相同。
    • 哎呀,好点子。我更改为 rank,它将返回 1-5、2-5 的重复值。如果您使用此查询来删除重复项,那应该可以。如果您需要返回这两个值,您可以将其加入到成本数据集,其中 dup = 2。我将在上面包含它。
    猜你喜欢
    • 2015-12-18
    • 2010-10-09
    • 2013-01-28
    • 2013-01-04
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-09
    相关资源
    最近更新 更多