这是mytable
customerID invoice payment
1 101 300
1 101 300
3 102 200
4 103 200
1 104 200
我想做的是,首先:分组发票,然后对分组发票的付款进行总计(300 + 200)
select customerID , sum(payment) as totalpaid from mytable WHERE
customerID ='1' group by `invoice`
预期结果是500。但是使用上面的代码我得到800。如何正确做到这一点?
答案 0 :(得分:2)
如果要排除重复项,请使用DISTINCT
:
SELECT
customerID,
SUM(payment) as totalpaid
FROM
(SELECT DISTINCT customerID, invoice, payment FROM customers)
GROUP BY customerID
对于customerID = 1
,您可以
SELECT
customerID,
SUM(payment) as totalpaid
FROM
(SELECT DISTINCT customerID, invoice, payment FROM customers)
WHERE customerID = 1
无需GROUP BY
。