0

早上好,

我有一个烦人的问题,我无法真正解决。我有一个这样的数据库表,显示每个人在日期范围内花费的资源(价值):

    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)执行此操作:获取每日金额,然后根据范围逐月检查在那里度过的天数,并将其乘以每日金额。

谢谢彼得

4

2 回答 2

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在这里

于 2013-04-27T16:51:17.057 回答
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。

于 2013-04-27T12:47:49.683 回答