我只需要在付款日期相同的情况下对列的数据求和。
以下是返回的数据:
judgment PaymentDate interestrate current1 paymentamount principalamount
2/1/2008 7/31/2010 9.00 5781.04 -315.07 -270.07
2/1/2008 7/31/2010 9.00 5781.04 272.59 227.59
以下是查询:
select tb1.judgment, fulldate as PaymentDate, m.interestrate, m.current1, paymentamount, principalamount from master m
inner join AARS_JudgmentsWithPA tb1 on tb1.jmacct = m.number
inner join courtcases cc on cc.accountid = m.number
where m.lastinterest != '2099-01-01 00:00:00.000'
and tb1.fulldate > tb1.judgment
and cast(tb1.PrincipalAmount as money) != 0
and tb1.judgment != ''
and m.number = 568463
对于提供的示例数据,我需要合并这些行,因为付款日期是相同的。因此,付款金额应缩减为(-270.07 + 227.59),即-42.48。
我尝试按照全额付款和付款金额进行分组,但是我希望我对每个列进行分组,然后再次返回这两行。
我错过了什么?
答案 0 :(得分:1)
您需要为未分组的列指定聚合。对于重复MIN()
的数字列,MAX()
或AVG()
是合适的。对于字符串列MIN()
或MAX()
可行。
select tb1.judgment,
fulldate as PaymentDate,
MIN(m.interestrate) AS interestrate,
MIN(m.current1) AS current1,
SUM(paymentamount) AS paymentamount,
SUM(principalamount) AS principalamount
from master m
inner join AARS_JudgmentsWithPA tb1 on tb1.jmacct = m.number
inner join courtcases cc on cc.accountid = m.number
where m.lastinterest != '2099-01-01 00:00:00.000'
and tb1.fulldate > tb1.judgment
and cast(tb1.PrincipalAmount as money) != 0
and tb1.judgment != ''
and m.number = 568463
group by tbl.judgment, fulldate
另一种选择是对重复和聚合其余列的列进行分组:
select tb1.judgment,
fulldate as PaymentDate,
m.interestrate,
m.current1,
SUM(paymentamount) AS paymentamount,
SUM(principalamount) AS principalamount
from master m
inner join AARS_JudgmentsWithPA tb1 on tb1.jmacct = m.number
inner join courtcases cc on cc.accountid = m.number
where m.lastinterest != '2099-01-01 00:00:00.000'
and tb1.fulldate > tb1.judgment
and cast(tb1.PrincipalAmount as money) != 0
and tb1.judgment != ''
and m.number = 568463
group by tbl.judgment, fulldate, m.interestrate, m.current1
答案 1 :(得分:0)
当您使用聚合函数时,您没有遗漏任何内容,在本例中为sum(),您必须按每个其他非聚合列进行分组。前几个句子以一种非常详细的方式解释:http://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html以及需要您按以下分组的函数列表:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html