正确使用Group By功能

时间:2013-07-04 08:47:00

标签: mysql group-by

我正在运行一个查询来查找我的数据库中缓慢移动的股票,但它给出的错误表明无条件使用group by条件。逻辑是我想找出过去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)

2 个答案:

答案 0 :(得分:3)

请改为尝试:

SELECT * 
FROM
(
    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
    GROUP BY itemmaster.item, stockbalance.qty
) AS t
WHERE saledate BETWEEN DATE_SUB(NOW(),INTERVAL 120 DAY) 
                   AND NOW()
  AND total_sales < (total_stock * 0.05)

答案 1 :(得分:3)

您需要将sum条件从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)