[英]SQL Sum() - 0 in field excluding row from aggregation?
Consider the following query: 考虑以下查询:
$query = "
SELECT a_orders.id, a_orders.billing,
SUM(a_order_rows.quant_refunded*a_order_rows.price*((100-a_orders.discount)*.01)) as refund_total,
SUM(a_order_rows.quant*a_order_rows.price*((100-a_orders.discount)*.01)) as order_total
FROM a_order_rows JOIN a_orders
ON a_order_rows.order_id = a_orders.id
WHERE a_order_rows.quant_refunded > 0
GROUP BY a_orders.id, a_orders.billing
ORDER BY a_orders.id DESC
LIMIT 50";
The two uses of SUM() are attempting to aggregate the order total and the total amount that has been refunded. SUM()的两种用法试图汇总订单总额和已退款的总额。 They are coming out correctly when when the quant_refunded field is not 0... for example take this data (excluding primary key, item_id for simplicity's sake, assuming each row is a unique item):
当quant_refunded字段不为0时,它们可以正确显示出来...例如,以该数据(为简单起见,假设主行,唯一行除外,假设每一行都是唯一的项,则不包括主键,item_id):
Table: a_order_rows
Fields: order_id, quant, quant_refunded
1, 1, 1
1, 2, 1
2, 1, 1
2, 1, 0
In the case of "order 1" the two aggregations are different and behave as expected. 在“顺序1”的情况下,这两个聚合是不同的,并且行为符合预期。 But for "order 2" the two numbers are coming out the same - both numbers are what I am expecting refund_total to be.
但是对于“第2阶”来说,这两个数字是相同的-这两个数字都是我期望的return_total。 It appears that the row with "0" in quant_refunded is being excluded from the order_total aggregation.
看来quantum_refunded中具有“ 0”的行已从order_total聚合中排除。
Hopefully this is explained thoroughly enough. 希望对此有足够的解释。 Please let me know if you need more info and I will revise.
如果您需要更多信息,请告诉我,我会进行修改。 THANKS!
谢谢!
$query = "
SELECT a_orders.id, a_orders.billing,
SUM(a_order_rows.quant_refunded*a_order_rows.price*((100-a_orders.discount)*.01)) as refund_total,
SUM(a_order_rows.quant*a_order_rows.price*((100-a_orders.discount)*.01)) as order_total
FROM a_order_rows JOIN a_orders
ON a_order_rows.order_id = a_orders.id
GROUP BY a_orders.id, a_orders.billing
HAVING MAX(a_order_rows.quant_refunded) > 0
ORDER BY a_orders.id DESC
LIMIT 50";
Change that to a HAVING clause. 将其更改为HAVING子句。 If any quant_refunded rows are > 0, the
HAVING MAX
will retain it. 如果任何quant_refunded行> 0,则
HAVING MAX
将保留它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.