Warm tip: This article is reproduced from serverfault.com, please click

Get total count of duplicates in column

发布于 2020-12-02 13:29:09

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)

Questioner
Still_learning
Viewed
0
Tim Biegeleisen 2020-12-02 21:34:15

Using analytic functions:

WITH cte AS (
    SELECT *, COUNT(*) OVER (PARTITION BY quantity) cnt
    FROM yourTable
)

SELECT COUNT(*)
FROM cte
WHERE cnt > 1;