2013-05-16 25 views
0

考慮以下查詢:SQL Sum() - 0在字段中排除聚集中的行嗎?

$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"; 

SUM的兩種用途()正試圖聚集訂單總額和已被退還的總量。他們是正確出來的時候,當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 

在這種情況下「訂單1」的兩個集合是不同的,並按預期行事。但對於「訂單2」這兩個數字是相同的 - 兩個數字都是我期待的refund_total。看來quant_refunded中帶有「0」的行將被排除在order_total聚合之外。

希望對此有足夠的解釋。請讓我知道你是否需要更多的信息,我會修改。謝謝!

+1

我很困惑。你的問題是「quant_refunded中帶有」0「的行被排除在外」,並且你的查詢有'WHERE a_order_rows.quant_refunded> 0'。查詢是不是故意刪除您要查找的行? –

+0

既然你這樣說,是的......這意味着我需要修改,所以當至少有一個加入的order_row的quant_refunded> 0時,包含所有的order_row條目。 – irregularexpressions

+0

將「WHERE a_order_rows.quant_refunded> 0」更改爲「WHERE SUM (a_order_rows.quant_refunded)> 0「不起作用。 – irregularexpressions

回答

1
$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"; 

將其改爲HAVING子句。如果任何quant_refunded行大於0,HAVING MAX將保留它。

+0

這工作完美,不知道存在HAVING子句。謝謝! – irregularexpressions