sql Count Date和sum的总和

时间:2015-01-07 08:53:57

标签: sql postgresql jasperserver

我想将数据安排到帐户对帐单格式

表A

Creditors name       Invoice No         Due date          Outstanding Amt
Company A            A001              1/8/2014            1500
Company B            A002              1/10/2014            300
Company B            A003              5/11/2014            900
Company B            A004              6/11/2014            50        
Company c            A005              31/12/2014           200

报表日期:2014年12月31日(总是根据当月改变),预期产出

Creditors name    0-30 Days    31-60 Days   61-90 Days   Over 90 Days   Amt Due        
Company A             0           0           0              1500         1500
Company B             0           950         0              300          1250
Company c            200          0           0               0           200

请帮助&谢谢

2 个答案:

答案 0 :(得分:0)

select "Creditors name",
       SUM(case when "Due date" >= current_date - 30 then "Outstanding Amt" end) as "0-30 Days",
       SUM(case when "Due date" between current_date - 31 and current_date - 60 then "Outstanding Amt" end) as "31-60 Days",
       SUM(case when "Due date" between current_date - 61 and current_date - 90 then "Outstanding Amt" end) as "61-90 Days",
       SUM(case when "Due date" < current_date - 90 then "Outstanding Amt" end) as "Over 90 Days",
       SUM("Outstanding Amt") as "Amt Due"
from "Table A"
group by "Creditors name"

日期和间隔总是很难处理,因为大多数dbms产品的行为都不同,我不知道你的dbms是如何工作的。所以你需要修改我的代码!

答案 1 :(得分:0)

下面的内容可能有效

Select 
creditor_name,
sum(case when datediff(day,due_date,getdate()) between 0 and 30 then [Outstanding Amt] else 0 end) as [0-30 days],
sum(case when datediff(day,due_date,getdate()) between 31 and 60 then [Outstanding Amt] else 0 end) as [0-30 days],
.
.
.
from table
group by creditor_name,