For example I have a Product table with count, but I would like to display only the values of the top 3 products based on the sum of their count.
Product | Date | Value |
---|---|---|
Product 1 | 2022-12-01 | 200 |
Product 1 | 2022-12-02 | 200 |
Product 2 | 2022-12-01 | 200 |
Product 2 | 2022-12-03 | 500 |
Product 3 | 2022-12-04 | 300 |
Product 3 | 2022-12-08 | 600 |
Product 4 | 2022-12-01 | 100 |
Product 4 | 2022-12-03 | 100 |
Product 5 | 2022-12-01 | 700 |
Product 5 | 2022-12-10 | 800 |
Based on the sample above, the sum of each product would be: Product 1 - 400 Product 2 - 700 Product 3 - 900 Product 4 - 200 Product 5 - 1,500
And I would like to display only the values of the top 3 products (Products 5, 3, and 2).
Product | Date | Value |
---|---|---|
Product 2 | 2022-12-01 | 200 |
Product 2 | 2022-12-03 | 500 |
Product 3 | 2022-12-04 | 300 |
Product 3 | 2022-12-08 | 600 |
Product 5 | 2022-12-01 | 700 |
Product 5 | 2022-12-10 | 800 |
I used to check first the product with the highest sum of count so I could use the result as a filter on my table. But I'd like to use 1 SQL query only instead of running 2 separate queries.
SELECT product, count(value) as prod_count
FROM product
GROUP BY product
ORDER BY prod_count
LIMIT 3