2017-05-25 40 views
-3

我寫了這個代碼,我發現這些值是在幾千噸時,他們應該頂多只有數百人。SQL SUM函數給出不正確的值

SELECT 
    C.CLIENTID, 
    SUM(NVL(B.FEE, 0)) AS TICKETS, 
    SUM(NVL(PU.QTY, 0) * NVL(P.PRICE, 0)) AS MERCH, 
    SUM(NVL(B.FEE, 0) + (NVL(P.PRICE, 0) * NVL(PU.QTY, 0))) AS Total 
FROM 
    CLIENT C 
    LEFT JOIN BOOKINGS B ON B.CLIENTID = C.CLIENTID 
    LEFT JOIN PURCHASE PU ON PU.CLIENTID = C.CLIENTID 
    LEFT JOIN PRODUCT P ON P.PRODUCTID = P.PRODUCTID 
GROUP BY 
    C.CLIENTID 
ORDER BY 
    C.CLIENTID ASC; 

這些是我得到的結果。

+----------+---------+-------+--------+ 
| CLIENTID | TICKETS | MERCH | TOTAL | 
+----------+---------+-------+--------+ 
| 1  | 0  | 0  | 0  | 
+----------+---------+-------+--------+ 
| 2  | 13650 | 0  | 13650 | 
+----------+---------+-------+--------+ 
| 3  | 17325 | 0  | 17325 | 
+----------+---------+-------+--------+ 
| 4  | 40950 | 20316 | 61266 | 
+----------+---------+-------+--------+ 
| 5  | 91875 | 71106 | 162981 | 
+----------+---------+-------+--------+ 
| 6  | 0  | 0  | 0  | 
+----------+---------+-------+--------+ 
| 7  | 4200 | 0  | 4200 | 
+----------+---------+-------+--------+ 
| 8  | 17850 | 6772 | 24622 | 
+----------+---------+-------+--------+ 
| 9  | 8400 | 0  | 8400 | 
+----------+---------+-------+--------+ 
| 10  | 8400 | 0  | 8400 | 
+----------+---------+-------+--------+ 
| 11  | 12600 | 0  | 12600 | 
+----------+---------+-------+--------+ 
| 12  | 8925 | 3386 | 12311 | 
+----------+---------+-------+--------+ 
| 13  | 8925 | 3386 | 12311 | 
+----------+---------+-------+--------+ 
| 14  | 4200 | 0  | 4200 | 
+----------+---------+-------+--------+ 
| 15  | 17325 | 0  | 17325 | 
+----------+---------+-------+--------+ 
| 16  | 105000 | 91422 | 196422 | 
+----------+---------+-------+--------+ 
+0

你是什麼表模式? –

+0

我認爲這是Oracle。請正確標記您的問題。 –

+2

爲什麼人們會標記多個RDBMS? 'mysql'和'sql-server'? +如何在沒有顯示輸入數據的情況下繼續? – niksofteng

回答

0

我不知道你的表是什麼,但嘗試內部聯接

SELECT 
    C.CLIENTID, 
    SUM(NVL(B.FEE, 0)) AS TICKETS, 
    SUM(NVL(PU.QTY, 0) * NVL(P.PRICE, 0)) AS MERCH, 
    SUM(NVL(B.FEE, 0) + (NVL(P.PRICE, 0) * NVL(PU.QTY, 0))) AS Total 
FROM 
    CLIENT C 
    INNER JOIN BOOKINGS B ON B.CLIENTID = C.CLIENTID 
    INNER JOIN PURCHASE PU ON PU.CLIENTID = C.CLIENTID 
    INNER JOIN PRODUCT P ON P.PRODUCTID = P.PRODUCTID 
GROUP BY 
    C.CLIENTID 
ORDER BY 
    C.CLIENTID ASC; 
+0

非常感謝你的幫助。幫助我進行了很多調試,並找到解決方案 –

+1

將其標記爲答案.. – asmgx

0

一個解決人誰可能會遇到這種用相同的問題,因爲我是;

SELECT C.CLIENTID, 
    SUM(NVL(B.FEE, 0)) AS TICKETS, 
    SUM(NVL(PU.QTY, 0) * NVL(P.PRICE, 0)) AS MERCH, 
    SUM(NVL(B.FEE, 0) + (NVL(P.PRICE, 0) * NVL(PU.QTY, 0))) AS Total 
FROM CLIENT C 
    LEFT JOIN BOOKINGS B ON B.CLIENTID = C.CLIENTID 
    LEFT JOIN PURCHASE PU ON PU.CLIENTID = C.CLIENTID 
    LEFT JOIN PRODUCT P ON PU.PRODUCTID = P.PRODUCTID 
GROUP BY C.CLIENTID 
ORDER BY C.CLIENTID ASC;