SQL SUM函数提供的值不正确

时间:2017-05-25 04:51:34

标签: mysql sql

我已经编写了这段代码,而且我发现这些代码的数量最多只有几百个。

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 |
+----------+---------+-------+--------+

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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;