2012-12-21 175 views
1

我有一個查詢,它返回來自客戶的貨物的SUM值以及shipment_id的分組。值是正確的。彙總時發生彙總錯誤

SELECT SUM(DISTINCT((article.unit_price * article.tax)*shipment.amount)) as subtotal 
    FROM shipment 
INNER JOIN customer ON customer.customer_id = shipment.customer_id 
INNER JOIN article ON shipment.article_id = article.article_id 
WHERE shipment.type_id = 2 
    AND shipment.customer_id = 947 
GROUP BY shipment.shipment_id 

當我刪除GROUP BY以從客戶獲得總價值返回的值不正確。

有人可以幫我解決這個問題嗎?

+0

你可以張貼一些示例數據? – Taryn

+0

爲什麼有DISTINCT? – SergeS

+0

1 - 不明白你爲什麼總結不同的值。如果客戶擁有同樣價格的相同商品中的兩件,那麼你肯定會希望它們都是你的總和。 2 - 不清楚爲什麼當你沒有選擇它時,通過shipment_id進行分組 - 你可能會得到幾行而不知道哪個是哪個。 –

回答

2

您的連接有問題。我可以想象,在查詢中sum(distinct)是有意義的。您使用不正確。發生的情況是,您在發貨過程中有重複的文章,並且貨件中的值可能不錯(可能只是貨件中的一篇文章)。但是,不同的貨物具有完全相同的文章和相同的數量。獨特刪除這樣的重複。

解決方法很簡單,只需取下distinct

SELECT SUM((article.unit_price * article.tax)*shipment.amount) as subtotal 
FROM shipment INNER JOIN 
    customer 
    ON customer.customer_id = shipment.customer_id INNER JOIN 
    article 
    ON shipment.article_id = article.article_id 
WHERE shipment.type_id = 2 AND shipment.customer_id = 947