MySQL:如何列出一列并总结另一列?

时间:2013-09-04 15:40:08

标签: mysql sum

我正在使用以下SQL:

  SELECT
    a.name as accountName,
    SUM((i.value - i.paidValue)) as oneMonth
  FROM insertions i
  JOIN contracts c ON i.contractId = c.id
  JOIN accounts a ON c.accountId = a.id
  WHERE i.value > i.paidValue
    AND i.isDeleted is FALSE
    AND i.isCanceled is FALSE
    AND i.month = 8
    AND i.year = 2013

它应该产生这样的输出:

accountName | oneMonth
CompanyA    | 3000 [ which is a sum of 1000, 1000, 1000 ]
CompanyB    | 1000

但它正在做的是:

accountName | oneMonth
CompanyA    | 4000 

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您忘记了分组

GROUP BY a.id

答案 1 :(得分:0)

SELECTa.name as accountName,SUM((i.value - i.paidValue)) as oneMonth
   FROM insertions i
JOIN contracts c ON i.contractId = c.id
JOIN accounts a ON c.accountId = a.id
   WHERE i.value > i.paidValue
    AND i.isDeleted is FALSE
    AND i.isCanceled is FALSE
    AND i.month = 8
    AND i.year = 2013
Group by a.name

这将有效..