-3

I need to find rows with duplicate order numbers in a table in SQL Server.

For example SELECT * shows:

No
-----
5001
5002
5003
5003
5003
5004
5005
5006
5006

I want to get

No
------
5003
5003
5003
5006
5006

Is it possible to write a query to do that?

Jack
  • 505
  • 1
  • 4
  • 17

3 Answers3

0

Although this question was answered thousand times on SO, use GROUP BY + HAVING:

SELECT No
FROM dbo.tablename
Group By No
Having Count(*) > 1
Tim Schmelter
  • 429,027
  • 67
  • 649
  • 891
0
SELECT S.No
  FROM [dbo].[Shows] S
  INNER JOIN (
      SELECT [No]
      FROM [dbo].[Shows]
      GROUP BY [No]
      HAVING COUNT(*) > 1
  ) J
    ON S.No = J.No
Yuriy Rypka
  • 1,687
  • 1
  • 18
  • 21
0

You can use COUNT() OVER() to get count of rows per No and, in an outer query, filter out all non-duplicate rows:

SELECT [No]
FROM (
   SELECT [No], COUNT(*) OVER (PARTITION BY [No]) AS cnt
   FROM mytable ) t
WHERE cnt > 1

Demo here

Giorgos Betsos
  • 69,699
  • 7
  • 57
  • 89