2013-11-21 43 views
0

我只需要在支付日期相同的情況下對列的數據進行求和。總計一個特定的列

這是返回的數據:

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。

我試圖按照fulldate和付款總額進行分組,但它要求我將每個列分組,然後再返回兩行。

我錯過了什麼?

+0

您正在使用哪個數據庫管理系統? Postgres的?甲骨文? –

+0

SSMS。我認爲這就是你要找的。 –

+0

我從來沒有聽說過一個名爲* SSMS *的DBMS--那是什麼? –

回答

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 
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

+0

必須有一種解決方法,我無法按其他列進行分組,因爲它然後返回兩行,這樣做會導致嘗試對支付日期相同的行進行求和。 –

+0

您可以禁用它,但是如果您將每列分組並取回多行,這意味着您將取回具有唯一值的數據。這將導致你正在看到的東西,在這種情況下你的principalamount字段有不同的數據,所以你得到每行獨特的一行數據。 –

+0

好吧我現在明白了。我一起刪除了principalamount列,因爲在這個計算中沒有必要。現在它返回一行。 –