0

我正在使用以下 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 

我究竟做错了什么?

4

2 回答 2

1

您忘记了 group by 子句

GROUP BY a.id
于 2013-09-04T15:48:42.340 回答
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

这将工作..

于 2013-09-04T15:59:04.020 回答