MySQL从日期范围生成每月细分

时间:2013-04-27 10:44:56

标签: mysql sql date

早上好,

我有一个唠叨的问题,我无法解决..我有一个这样的数据库表,显示在人的日期范围内花费的资源(值):

    id,name,startdate,enddate,value
    --------------------------------
    10,John,2012-01-14,2012-10-30,200000
    11,Jack,2012-02-01,2012-08-01,70000
    12,John,2012-05-01,2012-06-01,2000

我需要一个查询来创建这样的结果,按月汇总'价值',考虑部分月份

month, name, value
------------------    
2012-01, John, 9000
2012-02, John, 18000
2012-03, John, 18000
2012-04, John, 18000
2012-05, John, 20000
2012-06, John, 18000
2012-07, John, 18000
2012-08, John, 18000
2012-01, John, 18000
2012-02, Jack, 10000
2012-03, Jack, 10000
2012-04, Jack, 10000
2012-05, Jack, 10000
2012-06, Jack, 10000
2012-07, Jack, 10000
2012-08, Jack, 0

现在我知道如何通过循环程序(如PHP)进行此操作:获取每日金额,然后逐月检查根据范围花费多少天并将其乘以每日金额。 / p>

感谢 彼得

2 个答案:

答案 0 :(得分:1)

如果您没有日历表但无法创建日历表,则可以在查询中模拟虚拟日历表。这是一个应该回答你的问题的查询,它使用了这样一个虚拟表:

select m.startmonth,
       e.name, 
       coalesce(sum(r.value *
                    datediff(case when adddate(m.startmonth, interval 1 month) <
                                       r.enddate 
                                  then adddate(m.startmonth, interval 1 month) 
                                  else r.enddate end,
                             case when m.startmonth > r.startdate 
                                  then m.startmonth else r.startdate end) / 
                    datediff(r.enddate,r.startdate)),0) valueshare
from
(select cast('2012-01-01' as date) startmonth union all
 select cast('2012-02-01' as date) startmonth union all
 select cast('2012-03-01' as date) startmonth union all
 select cast('2012-04-01' as date) startmonth union all
 select cast('2012-05-01' as date) startmonth union all
 select cast('2012-06-01' as date) startmonth union all
 select cast('2012-07-01' as date) startmonth union all
 select cast('2012-08-01' as date) startmonth union all
 select cast('2012-09-01' as date) startmonth union all
 select cast('2012-10-01' as date) startmonth) m
cross join employees e
left join resources_spent r 
       on r.enddate > m.startmonth and 
          r.startdate < adddate(m.startmonth, interval 1 month) and
          r.name = e.name
group by m.startmonth, e.name
order by 2,1

SQLFiddle here

答案 1 :(得分:0)

我认为您需要一个日历表,每个日期都有一行。其他领域将是对您有用的任何领域,例如财政期间,假期等等。

然后,对于您的报告,您可以创建临时表并将其填充如下:

insert into YourTempTable
(id, date, amount)
select id, c.datefield, amount
from YourTable join Calendar c on datefield >= startdate
and datefield <= enddate
where whatever

从那里,你从YourTempTable和YourTable中选择,加入id。