2014-09-29 64 views
0

我試圖做一個查詢,獲取總訂單,所有訂單合併的總價格,並將它們按用戶名分組。SQL按字段加起來的總和數據

我有以下查詢:

SELECT 
    `customers`.`name`   AS 'name', 
    count(`orders`.`id`)  AS 'total orders', 
    sum(`orderDetails`.`price`) AS 'total price' 

FROM `customers` 

INNER JOIN `orders` 
ON 
    `orders`.`customer_id`  = `customers`.`id` 

INNER JOIN `orderDetails` 
ON 
    `orderDetails`.`order_id` = `orders`.`id` 

WHERE 
    `customers`.`company_id` = 1 

GROUP BY 
    `orders`.`id`, -- Removing this will have the users grouped correctly, 
         -- but display an invalid count. 
    `customers`.`id` 

目前我得到的結果類似這樣:

'John', '2', '2.0000' 
'Bill', '3', '3.0000' 
'Bill', '1', '1.0000' 
'John', '2', '2.0000' 
'John', '3', '3.0000' 

當現實:

John has 3 orders with a total price of 7.00 
Bill has 2 orders with a total price of 4.00 

有什麼辦法我可以修復這個?

+0

只有做到'GROUP BY customers.name' – 2014-09-29 19:20:59

+0

@ M.Ali這導致總訂單結束了具有相同值的總價 – Paradoxis 2014-09-29 19:22:31

+1

修復它你您的'OrderDetails'表中沒有一個名爲'Quantity'的列?總結價格似乎有點奇怪。 – 2014-09-29 19:27:16

回答

1

這裏的問題是,在不同層次的分組。然而,在這種情況下,你可以通過使用count(distinct

select 
    `customers`.`name` as 'name', 
    count(distinct `orders`.`id`) as 'total orders', 
    sum(`orderDetails`.`price`) as 'total price' 
from 
    `customers` 
     inner join 
    `orders` 
     on `orders`.`customer_id` = `customers`.`id` 
     inner join 
    `orderDetails` 
     on `orderDetails`.`order_id` = `orders`.`id` 
where 
    `customers`.`company_id` = 1 
group by 
    `customers`.`id`, 
    `customers`.`name` 
+0

啊謝謝你,這工作!我會接受幾個 – Paradoxis 2014-09-29 19:29:37

0

您只需要一組由聲明:

GROUP BY 
`customers`.`name` 
+0

這會導致訂單總量錯誤(與總價格具有相同的值) – Paradoxis 2014-09-29 19:27:15

+0

它不應該提供您正在使用的數據嗎? – NickHeidke 2014-09-29 19:28:42