2012-12-21 179 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