We can SUM (instead of COUNT) the value and GROUP BY the product.
Here we can use FETCH FIRST 3 ROWS WITH TIES to find for example two products having the identic 3rd highest sum.
So the entire query will be this one:
SELECT product, date, value
FROM product
WHERE product IN
(SELECT product
FROM product
GROUP BY product
ORDER BY SUM(value) DESC
FETCH FIRST 3 ROWS WITH TIES)
ORDER BY product, date;
We should mention the column/table naming should be improved if possible because having the same table name and column name "product" causes bad readability.
Furthermore the column "date" (wich is actually a SQL key word) should better be renamed to something more meaningful like for example "sellDate", same for the column "value".
Anyway, let's assume there is another product "product 6" which has the same sumed value (700) as product 2.
Then the above query will produce this outcome:
| 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 |
| Product 6 |
2022-12-01 |
600 |
| Product 6 |
2022-12-10 |
100 |
If it's not intended to show four products (or more if more have the same 3rd highest sum of value), we can just use LIMIT 3 instead:
SELECT product, date, value
FROM product
WHERE product IN
(SELECT product
FROM product
GROUP BY product
ORDER BY SUM(value) DESC
LIMIT 3)
ORDER BY product, date;
So we will get only three products again, one of those having the sumed value 700 (here product 2) will not be selected.
So the result of this query would be this:
| Product |
Date |
Value |
| Product 3 |
2022-12-04 |
300 |
| Product 3 |
2022-12-08 |
600 |
| Product 5 |
2022-12-01 |
700 |
| Product 5 |
2022-12-10 |
800 |
| Product 6 |
2022-12-01 |
600 |
| Product 6 |
2022-12-10 |
100 |
Or if we even want to say product 2 should be found instead of product 6, we can add the product to the ORDER BY clause:
SELECT product, date, value
FROM product
WHERE product IN
(SELECT product
FROM product
GROUP BY product
ORDER BY SUM(value) DESC, product
LIMIT 3)
ORDER BY product, date;
This will be the outcome for this query:
| 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 |
We can try out here: db<>fiddle