gpt4 book ai didi

mysql - 正确使用 Group By 功能

转载 作者:行者123 更新时间:2023-11-29 04:09:15 25 4
gpt4 key购买 nike

我正在运行一个查询来找出我数据库中流动缓慢的股票,但它给出了一个错误,指出按条件分组的使用无效。逻辑是我想找出过去 120 天的总销售额小于该项目截至日期的总库存的 5% 的项目。以下是查询:-

SELECT 
itemmaster.item as item,
stockbalance.qty as total_stock,
SUM(saleitems.saleqty) as total_sales
FROM itemmaster
JOIN stockbalance ON stockbalance.item = itemmaster.item
JOIN saleitems ON saleitems.item = itemmaster.item
WHERE saleitems.saledate BETWEEN DATE_SUB(NOW(),INTERVAL 120 DAY) AND NOW()
AND (SUM(saleitems.saleqty)) < (stockbalance.qty * 0.05)

最佳答案

您需要将求和条件从 WHERE 子句移动到 HAVING 子句。试试这个:

SELECT 
itemmaster.item as item,
SUM(stockbalance.qty) as total_stock,
SUM(saleitems.saleqty) as total_sales
FROM itemmaster
JOIN stockbalance ON stockbalance.item = itemmaster.item
JOIN saleitems ON saleitems.item = itemmaster.item
WHERE
saleitems.saledate BETWEEN DATE_SUB(NOW(),INTERVAL 120 DAY) AND NOW()
GROUP BY
itemmaster.item
HAVING
total_sales < (total_stock * 0.05)

关于mysql - 正确使用 Group By 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17465811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com