I need a query to count the total number of duplicates in a table, is there any way to do this?
If I have a table like this:
+------------+----------+ | item_name |quantity | +------------+----------+ | Calculator | 89 | | Notebooks | 40 | | Pencil | 40 | | Pens | 32 | | Shirts | 29 | | Shoes | 29 | | Trousers | 29 | +------------+----------+
I can’t use SELECT COUNT(quantity)
because it returns 2. (40 | 29
)
How can I return 5? (40 | 40 | 29 | 29 | 29
)
Advertisement
Answer
Using analytic functions:
WITH cte AS ( SELECT *, COUNT(*) OVER (PARTITION BY quantity) cnt FROM yourTable ) SELECT COUNT(*) FROM cte WHERE cnt > 1;