我試圖做一個查詢,獲取總訂單,所有訂單合併的總價格,並將它們按用戶名分組。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
有什麼辦法我可以修復這個?
只有做到'GROUP BY customers.name' – 2014-09-29 19:20:59
@ M.Ali這導致總訂單結束了具有相同值的總價 – Paradoxis 2014-09-29 19:22:31
修復它你您的'OrderDetails'表中沒有一個名爲'Quantity'的列?總結價格似乎有點奇怪。 – 2014-09-29 19:27:16