-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
  • 515
  • 1
  • 5
  • 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
  • 450,073
  • 74
  • 686
  • 939
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,937
  • 1
  • 19
  • 23
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
  • 71,379
  • 9
  • 63
  • 98