SQL ORDER BY - Why is it not working here?

橙三吉。 提交于 2019-12-11 17:54:33

问题


This is the table I have:

+---------------------+--------+----------+
| date                | sku    | quantity |
+---------------------+--------+----------+
| 2017-08-23 14:58:00 | 123333 |        2 |
| 2017-08-23 14:58:00 | 123333 |        1 |
| 2017-08-23 14:58:00 | 123333 |        1 |
| 2017-08-23 14:58:00 | 123337 |        2 |
| 2017-08-23 14:58:00 | 123335 |        1 |
| 2017-08-23 14:58:00 | 123331 |        1 |
| 2017-08-23 14:58:00 | 123332 |        2 |
| 2017-08-23 14:58:00 | 123333 |        1 |
| 2017-08-23 14:58:00 | 123334 |        1 |
| 2017-08-23 14:58:00 | 123334 |        3 |
+---------------------+--------+----------+

I would like to perform an select statement as follows:

select sku,sum(quantity) as 'total quant' from transactions
where DATE(date) between '2017-07-23' and '2017-09-23'
group by sku
order by quantity desc;

But I am getting this:

+--------+-------------+
| sku    | total quant |
+--------+-------------+
| 123332 | 2           |
| 123337 | 2           |
| 123333 | 5           |
| 123334 | 4           |
| 123335 | 1           |
| 123331 | 1           |
+--------+-------------+

Which is NOT in the order as I am expecting. Why is order by not working here?

SIDE NOTE My quantitycolumn is of data type int and I have tried casting as suggested in this post but to no avail.


回答1:


You are ordering by quantity. Because it is not aggregated, you are getting an arbitrary value from each group. You need to order by the total. One method is:

order by sum(quantity) desc

However, I would recommend assigning a reasonable alias (one that doesn't need to be escaped) and using that:

select sku,sum(quantity) as total_quantity
from transactions
where DATE(date) between '2017-07-23' and '2017-09-23'
group by sku
order by total_quantity desc;



回答2:


You need to order it by the SUM(quantity).

SELECT sku, SUM(quantity) AS 'total quant' 
FROM transactions
WHERE DATE(date) BETWEEN '2017-07-23' AND '2017-09-23'
GROUP BY sku
ORDER BY SUM(quantity) DESC;



回答3:


You should use:

order by sum(quantity)


来源:https://stackoverflow.com/questions/45878330/sql-order-by-why-is-it-not-working-here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!