Mysql根据列的SUM返回结果

时间:2013-09-17 17:22:20

标签: php mysql

我有一个查询,我需要让所有客户在一个月内花费的金额少于一定金额,并且只返回那些未达到配额的客户。

现在的查询如下。

SELECT cus.id, cus.email_address, COALESCE(SUM(credit_total),0) AS totalSpend
FROM customers AS cus
LEFT JOIN tasks_custs AS tsk ON tsk.user_id = cus.id
WHERE (
YEAR(date_ordered) = '2013'
AND MONTH(date_ordered) = '09'
AND paid = '1'
AND totalSpend < '300'
)

返回的错误是'where子句'中的未知列'totalSpend'。

我想知道的是,我可以用单个SQL查询来完成我想要做的事情,或者我将不得不选择所有客户并使用php检查支出。

我希望只让mysql返回我需要的结果。

2 个答案:

答案 0 :(得分:3)

使用聚合函数时,您需要使用HAVING关键字而不是WHERE

SELECT cus.id, cus.email_address, COALESCE(SUM(credit_total),0) AS totalSpend
FROM customers AS cus
LEFT JOIN tasks_custs AS tsk ON tsk.user_id = cus.id
WHERE (
YEAR(date_ordered) = '2013'
AND MONTH(date_ordered) = '09'
AND paid = '1')
GROUP BY cus.id
HAVING SUM(credit_total) < 30

如果您对此感兴趣,WHEREHAVING之间的区别为good explanation,请点击此处。但是如果你想要一个简短的总结,用我的话说,我会说这是:

  • WHERE条件在指定条件的任何分组之前应用,并且不能应用于聚合函数
  • HAVING在分组后应用 ,并且可以使用聚合函数来过滤结果集。

答案 1 :(得分:0)

这对你有什么用?我有分组的客户信息,并总结了总数,就像你有 - 除了我在分组数据后添加了一个HAVING CLAUSE。

SELECT 
    cus.id, 
    cus.email_address, 
    COALESCE(SUM(credit_total),0) AS totalSpend
FROM customers AS cus
LEFT JOIN tasks_custs AS tsk 
    ON tsk.user_id = cus.id
WHERE
    YEAR(date_ordered) = '2013'
    AND MONTH(date_ordered) = '09'
    AND paid = '1'
GROUP BY 
    cus.id, 
    cus.email_address
HAVING COALESCE(SUM(credit_total),0) < '300'