带有IF的MYSQL SUM()

时间:2013-10-18 10:41:40

标签: php mysql mysqli

我有三张桌子。这里简化了以便更好地理解。

simplified tables 有订单,还有作家。每个作者都分配了一个特定的 writer_alias 。作家为他完成的每个订单获得报酬,该订单也被批准(当order_status为1时)。但只有当核准订单总额的总和超过200美元时才会这样。

我需要计算ACID_COST或IMMEDIATE_PAYABLE,它等于任何总和大于200美元且该特定订单的payment_status为0的作家的总和。我不确定我是否能在这里解释它。这是我达到的目的,但它只计算所有已批准订单金额的总和。

"SELECT SUM(tblpayment.amount) AS PAYABLES FROM tblpayment, tblorder WHERE tblorder.order_alias=tblpayment.order_alias AND tblorder.order_status=1 AND tblpayment.payment_status=0"

在这种情况下,此处的期望答案可能为0,因为writer_alias(16)批准的金额为30,小于200,而writer_alias(15)批准的金额为10,再次小于200.

任何帮助将不胜感激。

修改 更正的表格图片在这里。

enter image description here

2 个答案:

答案 0 :(得分:1)

您不能在WHERE子句中使用聚合函数的结果。相反,您应该使用HAVING,如下所示:

SELECT tblorder.writer_alias, SUM(tblpayment.amount) AS PAYABLES
FROM tblpayment, tblorder
WHERE tblorder.order_alias = tblpayment.order_alias
  AND tblorder.order_status = 1
  AND tblpayment.payment_status = 0
GROUP BY tblorder.writer_alias
HAVING SUM(tblpayment.amout) > 200

答案 1 :(得分:0)

SELECT SUM(tblpayment.amount) AS PAYABLES 
FROM   tblpayment, tblorder 
WHERE  tblorder.order_alias=tblpayment.order_alias 
AND    tblorder.order_status=1 
AND    tblpayment.payment_status=0
and    PAYABLES > 200
group by writer_alias

这样的东西?