0

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

现在的查询如下。

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 只返回我需要的结果。

4

2 回答 2

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看这里的区别。但如果你想要一个快速的总结,用我的话来说,我会说是这样的:

  • WHERE条件在指定条件的任何分组之前应用,并且不能应用于聚合函数
  • 在分组后HAVING应用,可以使用聚合函数过滤结果集。
于 2013-09-17T17:26:01.920 回答
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'
于 2013-09-17T17:24:48.723 回答