查找分配给多个唯一值的重复值

时间:2015-06-22 15:32:41

标签: mysql sql sql-server sql-server-2008

我需要一个可以比较两列的查询(DBVersionKey,Desc19)。 逻辑 - 如果相同的Desc19用于多个DBVersionKey,则仅返回这些结果。以下是数据范围(摘录)

数据样本

DBVersionKey    Desc19
2491            W25170206H
2492            W25170212H
2493            W25170218H
2494            W25170224H
9129            40761KB18X
9191            40761KB18X

EXPECTED RESULT
DBVersionKey    Desc19
9129            40761KB18X
9191            40761KB18X

*我尝试过GROUP BY,HAVING COUNT和许多其他理论解决方案

我不希望查询包含数据值的任何细节,因为可能会有大量受影响的记录

表名 - 表_A

3 个答案:

答案 0 :(得分:1)

WITH CTE AS (SELECT DBVersionKey, Desc19, ROW_NUMBER()OVER(PARTITION BY Desc19
ORDER BY Desc19) RN
FROM Table_A)

SELECT * FROM CTE WHERE RN > 1

我建议使用带行号分区的公用表表达式。这将创建Desc19的每个实例的计数(RN)。

我现在无法测试查询,但请让我了解您的结果,我可以从那里进行调整。

修改

如果DBVersionKey不是唯一值,我会尝试:

SELECT DISTINCT DBVersionKey, Desc19, COUNT(*)
FROM Table_A
Group by DBVersionKey, Desc19

如果效果更好,请告诉我。

编辑2

再一次,我无法测试它。添加到第一个建议的查询:

WITH CTE AS (SELECT DBVersionKey, Desc19, ROW_NUMBER()OVER(PARTITION BY Desc19 ORDER BY Desc19) RN 
FROM (SELECT DISTINCT DBVersionKey, Desc19 FROM Table_A GROUP BY DBVersionKey, Desc19)

SELECT * FROM CTE WHERE RN > 1

答案 1 :(得分:0)

select
    a.*
from
    Table_A as a
inner join
    (select Desc19
     from Table_A
     group by Desc19
     having count(*) > 1) as b
  on a.Desc19 = b.Desc19 ORDER BY Desc19

答案 2 :(得分:0)

alybaba726基于EDIT 2的正确解决方案

WITH CTE AS (SELECT DBVersionKey, Desc19, ROW_NUMBER()OVER(PARTITION BY Desc19
    ORDER BY Desc19) RN FROM ix_spc_planogram GROUP BY DBVersionKey, Desc19)
SELECT * FROM CTE
    WHERE RN > 1
    ORDER BY RN