🐘PostgreSQL ❗ Beats 97.20% ❗ Simple solution with GROUP BY and HAVING filtering by COUNT
Approach\nThis SQL query you\'re writing aims to find customers who have purchased every product in the product table. To achieve this, you need to count the di
# Approach\nThis SQL query you\'re writing aims to find customers who have purchased every product in the product table. To achieve this, you need to count the distinct `product_key` each customer has purchased and compare it to the total number of products.\n\n1. **Main Query**:\n   - `SELECT customer_id`: Selects the customer IDs.\n   - `GROUP BY customer_id`: Groups the results by `customer_id` to aggregate their purchases.\n\n2. **HAVING Clause**:\n   - `HAVING COUNT(DISTINCT product_key)`: Counts the distinct `product_key` values each customer has.\n   - `= (SELECT COUNT(*) FROM product)`: Compares this count to the total number of products in the `product` table. This subquery returns the total number of products available.\n\nThis query ensures that only those customers who have purchased every single product are selected.\n\n\n# Code\n```\nSELECT customer_id FROM customer\nGROUP BY customer_id\nHAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM product)\n```
['PostgreSQL']