sum-after-group-by

kd3sttzy  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(313)

这是我的table

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。如何正确操作?

huwehgph

huwehgph1#

如果要排除重复项,请使用 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 .

相关问题