查找重复项,但在结果中包含重复项和其他列

时间:2017-02-16 20:39:00

标签: sql sql-server

我想在表格中的两个不同列上找到重复项,但也要在结果中包含其他列值。比如行id。我正在使用SQL SERVER 2012

这是我到目前为止所做的:

SELECT rowID, appID, spNumber, spName, date_submitted 
FROM myTable
GROUP BY appID
HAVING COUNT(*) > 1

上述查询的问题在于它将所有重复项分组为一行。我想要显示所有重复项。我还想找到appID和spNumber字段的所有重复项。这就是我希望结果数据的样子。我只想显示那些应用程序和SPDUMBER是重复的行。

rowID   |   appID  |  spNumber  |  spName  |  date_submitted
-------------------------------------------------------------
  34    |    832   |     1      | Bob Smith|   01/01/2010
  36    |    832   |     1      | Joe Bob  |   05/01/2010
  54    |    901   |     2      | Sue Joe  |   03/01/2010
  57    |    901   |     2      | Pat Joh  |   04/01/2010
  59    |    901   |     2      | Tim Sue  |   03/01/2010
  64    |    951   |     1      | Jim Bob  |   06/01/2010
  67    |    951   |     1      | Sam Sue  |   09/01/2010

3 个答案:

答案 0 :(得分:1)

那将是

SELECT rowID, appID, spNumber, spName, date_submitted 
FROM myTable
JOIN (
    SELECT appID
    FROM myTable
    GROUP BY appID, spNumber
    HAVING COUNT(*) > 1
) dups ON myTable.appID = dups.appID AND dups.spNumber = myTable.spNumber

答案 1 :(得分:1)

ROW_NUMBER()会为您完成此操作。只需确保选择行号大于1的行,您只能根据PARTITION BY中的两列获得重复项

示例:

SELECT rowID, appID, spNumber, spName, date_submitted 
FROM (
    SELECT t.*, ROW_NUMBER() OVER (PARTITION BY appID, spNumber ORDER BY appID) AS rn
    FROM myTable t
) x
WHERE rn > 1

答案 2 :(得分:0)

如果你的DBMS支持Windowed Aggregates,那很简单:

with cte as 
 (
   SELECT rowID, appID, spNumber, spName, date_submitted,
      count(*) over (partition by appID) as cnt -- count per appID
   FROM myTable
   GROUP BY appID
 )
SELECT  rowID, appID, spNumber, spName, date_submitted
FROM cte
WHERE cnt > 1