1

我有这个一般的想法来查找从这篇文章中获取的重复值: Select statement to find duplicates on certain fields

select field1,field2,field3, count(*)
  from table_name
  group by field1,field2,field3
  having count(*) > 1

这非常适合查找重复项,但我还需要提取一个唯一编号,在这种情况下,一个“订单号”列与返回的每一行一起出现。这个唯一值不能在上面的方法中使用,因为这将不会返回任何行,因为没有任何行是完全重复的。我需要能够返回这些数据,但还要找到在表中多次出现的记录。我认为这可以通过联合或使用存在来完成,但不确定如何实现。有任何想法吗?

样本结果理念:

order number, field1, field2, field3
123             a       b        c
456             d       e        f
789             a       b        c

会希望它像这样返回订单号 123 和 789:

order number, field1, field2, field3
123             a       b        c
789             a       b        c   
4

2 回答 2

3
;with a as
(
select count(*) over (partition by field1,field2,field3) count, order_number, field1,field2,field3
from table_name
)
select order_number, field1,field2,field3 from a where count > 1
于 2013-07-19T15:41:25.853 回答
1

我不完全确定这是否是您想要的,但听起来可能吗?

select min(t2.order_no), t2.field1, t2.field2, t2.field3, t1.cnt
from table_name t2, (
    select field1,field2,field3, count(*)
      from table_name
      group by field1,field2,field3
      having count(*) > 1
      ) t1
where t1.field1 = t2.field1      
and t1.field2 = t2.field2
and t1.field3 = t2.field3
group by t2.field1, t2.field2, t2.field3, t1.cnt

对于您的去重子查询中返回的每条记录,外部查询将附加到该记录与给定字段组合匹配的最小“订单号”。如果这不是您要查找的内容,请澄清。一些样本数据和样本输出会有所帮助。

编辑:从您发布的示例数据来看,您似乎只想返回有重复的记录。如果这就是你要找的东西,试试这个:

select * 
from  table_name t2
where exists (
    select field1,field2,field3, count(*)
      from table_name t1
      where t1.field1 = t2.field1      
      and t1.field2 = t2.field2
      and t1.field3 = t2.field3 
      group by field1,field2,field3
      having count(*) > 1
      )

SQLFiddle

于 2013-07-19T15:40:58.257 回答