我有一个表格(Order_line_t),格式如下:
Order_ID Product_ID Quantity
-------- ---------- --------
1001 1 2
1001 2 2
1001 4 1
1002 3 5
1003 3 1
1004 6 2
1004 8 2
1005 4 4
1006 1 1
1006 5 2
1006 7 2
1007 1 3
1007 2 2
1008 3 2
1008 8 3
1009 4 2
1009 7 3
1010 8 10
我的目标是显示按每个产品的降序流行排序的总数量,如下所示:(我使用了当前查询并点击了降序过滤器的列Total_Quantity来实现此结果)
Product_ID Total_Quantity
---------- --------------
8 15
4 8
3 8
7 5
1 5
2 4
6 2
5 2
我一直在努力解决这个问题3个小时,我不知道我的错误在哪里。我当前的SQL查询是这样的:
SELECT Product_ID, SUM(Quantity) AS Total_Quantity
FROM Order_line_t
GROUP BY Product_ID
我的查询结果如下:
Product_ID Total_Quantity
---------- --------------
1 5
2 4
3 8
4 8
5 2
6 2
7 5
8 15
先谢谢,我刚开始学习SQL。请耐心等待。
答案 0 :(得分:0)
SELECT Product_ID, SUM(Quantity) AS Total_Quantity
FROM Order_line_t
GROUP BY Product_ID
ORDER BY SUM(Quantity) DESC;
OR
SELECT Product_ID, Total_Quantity
FROM
(
SELECT Product_ID, SUM(Quantity) AS Total_Quantity
FROM Order_line_t
GROUP BY Product_ID
) SQ
ORDER BY Total_Quantity DESC;