列Sum和子查询给出错误

时间:2013-03-01 10:52:14

标签: mysql having

我有一张表,我想知道两列总和的未结余额

表格看起来像这样

journalid | senderid | sourcenr | accountnr | debitamount | creditamount | trxdate

SQL QUERY

 select j.senderid,

 (sum(j.debitamount)-(select sum(j2.creditamount)as balance from
 journal j2 where j2.sourcenr = j.sourcenr and j2.ccaountnr =
 3993200))as outstanding

  from journal j

 where j.accountnr = 3993200

 and( j.trxdate >= '2012-12-31' and j.trxdate < '2013-01-31')

 group by 1

 having (sum(j.debitamount)-(select sum(j2.creditamount)as balance from
 journal j2 where j2.source = j.source and j2.accnr = 3993200)) > 0

 order by 1

我收到以下错误 -

  

选择列表中的表达式无效(不包含在   聚合函数或GROUP BY子句。)

如果我添加sourcenr字段(如下所示)

 select j.senderid,
         j.sourcenr,

    (sum(j.debitamount)-(select sum(j2.creditamount)as balance from
 journal j2 where j2.sourcenr = j.sourcenr and j2.ccaountnr =
 3993200))as outstanding

    from journal j

 where j.accountnr = 3993200

 and( j.trxdate >= '2012-12-31' and j.trxdate < '2013-01-31')

 group by 1 ,2

 having (sum(j.debitamount)-(select sum(j2.creditamount)as balance from
 journal j2 where j2.source = j.source and j2.accnr = 3993200)) > 0

 order by 1

然后我没有收到错误,但我没有得到唯一行的senderid 请帮助 !!!

0 个答案:

没有答案