I'm currently trying to get the most popular productID from my MSSQL Database. This is what the table looks like (With a bit of dummy data):
OrderItems:
+--+-------+--------+---------+
|ID|OrderID|Quantity|ProductID|
+--+-------+--------+---------+
| 1| 1| 1| 1|
| 2| 1| 1| 2|
| 3| 2| 1| 1|
| 4| 2| 50| 2|
The OrderID field can be ignored, but I need to find the most popular ProductID's from this table, ordering them by how often they occur. The results set should look something like this:
+--------+
|PoductID|
+--------+
| 2|
| 1|
As ProductID 2 has a total quantity of 51, it needs to come out first, followed by ProductID 1 which only has a total quantity of 2.
(Note: Query needs to be compatible back to MSSQL-2008)
SELECT
productID
FROM
yourTable
GROUP BY
productID
ORDER BY
SUM(Quantity) DESC
GROUP BY allows SUM(), but you don't have to use it in the SELECT to be allowed to use it in the ORDER BY.
select ProductID
from OrderItems
group by ProductId
order by sum(Quantity) desc;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With