Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL needed to get most popular product based also off a quantity

Tags:

sql

sql-server

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)

like image 626
JakeJ Avatar asked Jan 26 '26 20:01

JakeJ


2 Answers

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.

like image 147
MatBailie Avatar answered Jan 28 '26 11:01

MatBailie


select ProductID
from OrderItems
group by ProductId
order by sum(Quantity) desc;
like image 45
Csaba Benko Avatar answered Jan 28 '26 10:01

Csaba Benko