I’m not sure how to word the question for the title. If there is a correct way to word this question better, I would appreciate it.
I have a denormalized table, records, with columns:
biz_address, customer_name, dept_ID, order_ID, order_amount.
biz_address and customer_name have duplicate column entries.
How can I get list of all orders for addresses with more than 5 orders per address?
What I want is a result set like so…
+-----------------+-----------+------------+----------+-----------+
| biz_address | customer_name | dept_ID | order_ID | order_amount |
+-----------------+-----------+------------+----------+-----------+
| 100 CLAY DR | REAL | 1 | 54 | 60 |
| 100 CLAY DR | REAL | 2 | 55 | 4 |
| 100 CLAY DR | REAL | 3 | 56 | 5 |
...
| 11 MOORE ST | ABCO | 10 | 67 | 7 |
| 11 MOORE ST | ABCO | 11 | 78 | 2 |
| 11 MOORE ST | ABCO | 12 | 79 | 4 |
| 11 MOORE ST | ABCO | 13 | 80 | 8 |
I know how to get a count:
SELECT biz_address, customer_name, order_ID, COUNT(*)
FROM records
GROUP BY customer_name
HAVING COUNT(*) > 5;
Which returns this…
+----------------+------------+------------+----------+
| biz_address | customer_name | order_ID | COUNT(*) |
+--------+------------+---------------+----------+
| 100 CLAY DR | REAL | 54 | 6 |
| 11 MOORE ST | ABC | 67 | 8 |
Thanks
2
Answers
Join your original table with a subquery that gets all the addresses with the specified number of duplicates.
Here’s an alternative solution using
COUNT()
as a window function instead of an aggregation function.Window functions require MySQL 8.0 or later.