这是我的表格:
+---------------------+--------+----------+
| 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 |
+---------------------+--------+----------+
我想按如下方式执行select语句:
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;
但我得到了这个:
+--------+-------------+
| sku | total quant |
+--------+-------------+
| 123332 | 2 |
| 123337 | 2 |
| 123333 | 5 |
| 123334 | 4 |
| 123335 | 1 |
| 123331 | 1 |
+--------+-------------+
这不符合我的预期。 为什么订单不在这里工作?
SIDE NOTE 我的quantity
列的数据类型为int
,我已根据this post中的建议尝试投放但无效。
答案 0 :(得分:6)
您按数量订购。因为它没有聚合,所以您从每个组中获取任意值。你需要按总额订购。一种方法是:
order by sum(quantity) desc
但是,我建议指定一个合理的别名(一个不需要转义的别名)并使用它:
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;
答案 1 :(得分:2)
您需要按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;
答案 2 :(得分:0)
您应该使用:
exclude