查找具有给定条件的所有重复行

时间:2017-08-26 16:25:12

标签: sql database oracle

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

我写这个查询

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

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

5 个答案:

答案 0 :(得分:0)

您可以选择使用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
  ) 

答案 1 :(得分:0)

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

  

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

此处<> 不等于的运营商。 我希望它能帮到你:)。

答案 2 :(得分:0)

这就是你需要的:

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

如果您还希望列出重复的ID - 费用对,请删除DISTINCT

答案 3 :(得分:0)

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

  

SELECT id,cost from Fruit a WHERE(SELECT COUNT(*)FROM Fruit b WHERE a.cost = b.cost and a.id&lt;&gt; b.id)&gt; 1

此处&lt;&gt; 是sql中不等于的运算符。

答案 4 :(得分:-1)

这很有效。把它放在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