SQL需要根据数量获得最受欢迎的产品

Jak*_*keJ 2 sql sql-server

我目前正试图从我的MSSQL数据库中获取最受欢迎的productID.这就是表格的样子(带有一些虚拟数据):

的OrderItems:

+--+-------+--------+---------+
|ID|OrderID|Quantity|ProductID|
+--+-------+--------+---------+
| 1|      1|       1|        1|
| 2|      1|       1|        2|
| 3|      2|       1|        1|
| 4|      2|      50|        2|
Run Code Online (Sandbox Code Playgroud)

可以忽略OrderID字段,但我需要从该表中找到最受欢迎的ProductID,按它们发生的频率对它们进行排序.结果集应如下所示:

+--------+
|PoductID|
+--------+
|       2|
|       1|
Run Code Online (Sandbox Code Playgroud)

由于ProductID 2的总数量为51,因此需要首先出现,然后是ProductID 1,其总数量为2.

(注意:查询需要与MSSQL-2008兼容)

Mat*_*lie 6

SELECT
  productID
FROM
  yourTable
GROUP BY
  productID
ORDER BY
  SUM(Quantity) DESC
Run Code Online (Sandbox Code Playgroud)

GROUP BY允许SUM(),但您不必在SELECT允许中使用它ORDER BY.