2016-02-04 139 views
1

我試圖創建我們的訂單的摘要報告,但無法在單個查詢中提取所有我需要的數據。一個列的MySQL SUM,ID列的DISTINCT

我想這些數據中提取:

  • 小計 - 所有訂單的總和deliveryTotal
  • 訂單 - - DISTINCT orderIds的COUNT
  • 量全部出售價格
  • 交付總量的SUM - 所有訂購數量的總和

訂單表(此示例簡化)

| orderId | deliveryTotal | total | 
|---------|---------------|-------| 
| 1  | 5    | 15 | 
| 2  | 5    | 15 | 
| 3  | 7.50   | 27.50 | 

訂單項目表

| orderItemId | orderId | productId | salePrice | quantity | 
|-------------|---------|-----------|-----------|----------| 
| 1   | 1  | 1   | 10  | 1  | 
| 2   | 2  | 1   | 10  | 1  | 
| 3   | 3  | 1   | 10  | 1  | 
| 4   | 3  | 2   | 10  | 1  | 

我提取這些數據當前的查詢是

SELECT 
    SUM(i.salePrice * i.quantity) as subtotal, 
    SUM(DISTINCT o.deliveryTotal) as deliveryTotal, 
    COUNT(DISTINCT o.orderId) as orders, 
    SUM(i.quantity) as quantity 
FROM orderItems i 
INNER JOIN orders o ON o.orderId = i.orderId 

這會導致正確的分類彙總,訂單數和數量的總和。但是當我在17.50之後,送貨總額返回爲12.50。如果我SUM(o.deliveryTotal)它將返回25.

編輯:期望的結果

| subtotal | deliveryTotal | orders | quantity | 
|----------|---------------|--------|----------| 
| 40.00 | 17.50   | 3  | 4  | 
+0

你能給SQL小提琴到底是什麼? – Sadikhasan

+0

@Sadikhasan在這裏它是http://sqlfiddle.com/#!9/02cb0/1 –

+0

更新的問題與預期的結果 – Nick

回答

3

由於的加入,SUM(DISTINCT deliveryTotal)骨料被施加到包括值5, 5, 7.5, 7.5(不同5 + 7.5 = 12.5)行集。

該行的SUM()作用於與orderItems的加入成爲,如果你只是做

SELECT o.* 
FROM orderItems i 
INNER JOIN orders o ON o.orderId = i.orderId 

而是你所要求的在deliveryTotal所有值的SUM()更加明顯,不論他們的地位。這意味着您需要將聚合應用於不同的級別。

由於您以後不打算添加GROUP BY,因此最簡單的方法是使用子查詢,其目的僅在於獲取整個表中的SUM()

SELECT 
    SUM(i.salePrice * i.quantity) as subtotal, 
    -- deliveryTotal sum as a subselect 
    (SELECT SUM(deliveryTotal) FROM orders) as deliveryTotal, 
    COUNT(DISTINCT o.orderId) as orders, 
    SUM(i.quantity) as quantity 
FROM orderItems i 
INNER JOIN orders o ON o.orderId = i.orderId 

子選擇通常是灰心了,但不會有針對再選擇一個顯著的性能損失,但沒有使用它聯接的替代方法不同。無論如何,計算都必須在現有連接的單獨聚合上完成。其他方法會在FROM子句中放置子查詢CROSS JOIN,該子句執行與我們在子查詢中放置的相同的操作。性能將是相同的。

+0

(SQLfiddle現在沒有響應我發佈的驗證結果,但我把它加載到我的測試數據庫,它確實工作) –

1
在內心的選擇每筆訂單

選擇比概括起來

Select 
SUM(subtotal) as subtotal, 
sum(deliveryTotal) as deliveryTotal, 
count(1) as orders, 
sum(quantity) as quantity 
from (
SELECT 
    SUM(i.salePrice * i.quantity) as subtotal, 
    o.deliveryTotal as deliveryTotal, 
    SUM(i.quantity) as quantity 
FROM orders o 
INNER JOIN orderItems i ON o.orderId = i.orderId 
group by o.orderId) as sub 
0

下面的查詢結果,你需要

SELECT SUM(conctable.subtotal), 
SUM(conctable.deliveryTotal), 
SUM(conctable.orders), 
SUM(conctable.quantity) from 
(SELECT SUM(i.salePrice * i.quantity) as subtotal, 
    o.deliveryTotal as deliveryTotal, 
    COUNT(DISTINCT o.orderId) as orders, 
    SUM(i.quantity) as quantity 
FROM orderItems i 
JOIN orders o ON o.orderId = i.orderId group by i.orderid) as conctable;