简体   繁体   English

如何在jasperreports中汇总一个月中的值(总和)(每个月应为前一个月的总和)

[英]How to aggregate (sum) values over month in jasperreports (each month should be the sum of all month before)

I want to do a report with jasperreports that aggregates our contracts over the month but adding all new and old contracts to the month. 我想用jasperreports做一个报告,该报告汇总我们一个月内的合同,但是将所有新旧合同添加到该月中。 The database is a mysql database. 该数据库是一个mysql数据库。 My SELECT would look like this with example data below: 我的SELECT看起来像下面的示例数据:

SELECT month(contract_date), amount
FROM contracts
WHERE year(contract_date)=2013
GROUP BY month(contract_date)

1.1.2013 300
1.1.2013 500
1.2.2013 250
1.3.2013 250

Now i get: 现在我得到:

1 800
2 250
3 250
...

But i would like to have: 但我想拥有:

1 800
2 1050
3 1300
...

So each month contains the amount of all month before. 因此,每个月包含前一个月的所有金额。

I dont mind if i can do this in SQL or with jasperreports/iReport, so any solution is welcome. 我不在乎我是否可以在SQL中或使用jasperreports / iReport进行此操作,因此欢迎任何解决方案。 Is there any way i can do this? 有什么办法可以做到吗?

MySQL doesn't have CTEs which is inconvenient, but a view will do in a pinch. MySQL没有CTE,这很不方便,但是视图会很紧迫。

create view MonthlyTotals as
    select  Month( ContractDate ) as ContractMonth, Sum( ContractQty ) as TotalQty
    from    contracts
    group by ContractMonth;

Now we can join the view with itself, maintaining a running total of the month and all previous months: 现在,我们可以将视图与其自身连接起来,并保持该月和之前所有月的运行总计:

select  t1.ContractMonth, t1.TotalQty, Sum( t2.TotalQty ) as RunningTotal
from    MonthlyTotals t1
join    MonthlyTotals t2
  on    t2.ContractMonth <= t1.ContractMonth
group by t1.ContractMonth;

The output matches your desired output, as seen at SQL Fiddle . 输出与您所需的输出匹配,如SQL Fiddle所示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM