2014-10-28 75 views
0

Im做一個查詢在那裏我做2個求和,但它發出了一種怪異的結果SQL 2個求和給予了不正確的結果

SELECT 
    SUM(Details.price * Details.quantity) AS total_amount, 
    SUM(Payment.amount_paid) as paid_amount 
FROM 
    Details, 
    Invoice 
LEFT JOIN 
    Payment ON Invoice.id = Payment.fk_invoice_id 
WHERE 
    AND Invoice.id = 1 
    AND Invoice.id = Details.fk_invoice_id 
GROUP BY Details.fk_invoice_id; 

什麼是目前發生的事情是可以說有在支付3行相匹配的選擇標準並且只有1個細節,total_amount中的總和乘以3,但是paid_amount是正確的。然後讓我們說明細節中有2項與條件相符,付款方式爲1,paid_amount乘以2,但total_amount是正確的。任何提示都會很棒,謝謝!

架構

Invoice 
    id 
    Name.... 


Details 
    id 
    fk_invoice_id 
    name 
    price 
    quantity 

Payment 
    id 
    fk_invoice_id 
    amount_paid 

更多細節:

我正在努力簡化我的職位,但只是添加

客戶有許多發票

我只能是一個參考給客戶,所以customer.id是發票中的外鍵,即時嘗試獲取特定客戶的所有發票。

回答

1

所有你想要做的就是從細節和東西從發票付款的東西。但你正在加入所有相關記錄。所以說,有3個詳細記錄和發票,那麼你乘以2的詳細結果2條的繳費記錄,並通過3.付款結果您可以鴻溝:

SELECT 
    SUM(Details.price * Details.quantity)/GREATEST(COUNT(DISTINCT Payment.id),1) AS total_amount, 
    SUM(Payment.amount_paid)/COUNT(DISTINCT Details.id) as paid_amount 
FROM Details 
JOIN Invoice ON Invoice.id = Details.fk_invoice_id AND Invoice.id = 1 
LEFT JOIN Payment ON Invoice.id = Payment.fk_invoice_id 
GROUP BY Invoice.id; 

或者乾脆不參加什麼切不可加入。這裏有一種方法:

SELECT 
    (SELECT SUM(Details.price * Details.quantity) FROM Details WHERE Details.fk_invoice_id = Invoice.id) AS total_amount, 
    (SELECT SUM(Payment.amount_paid) FROM Payment WHERE Payment.fk_invoice_id = Invoice.id) AS paid_amount 
FROM Invoice 
WHERE id = 1; 

這裏是另一個,其中前加入聚合完成。 (我們不需要發票表無論如何,順便說一句,我在這裏將其刪除。)

SELECT 
    d.total_amount, 
    p.paid_amount 
FROM 
(
    SELECT fk_invoice_id, SUM(price * quantity) as total_amount 
    FROM Details 
    GROUP BY fk_invoice_id 
) d ON d.fk_invoice_id = Invoice.id 
LEFT JOIN 
(
    SELECT fk_invoice_id, SUM(Payment.amount_paid) as paid_amount 
    FROM Payment 
    GROUP BY fk_invoice_id 
) p ON p.fk_invoice_id = Invoice.id 
WHERE d.fk_invoice_id = 1; 

只要你只是尋找一個發票號,所有上述語句可以simplyfied當然。例如:

SELECT 
    (SELECT SUM(Details.price * Details.quantity) FROM Details WHERE Details.fk_invoice_id = 1) AS total_amount, 
    (SELECT SUM(Payment.amount_paid) FROM Payment WHERE Payment.fk_invoice_id = 1) AS paid_amount;