滚动月份的Rails或sql逻辑

时间:2014-11-17 21:36:02

标签: mysql sql ruby-on-rails ruby

我的桌子是这样的

Allocated_cost,Start_date,End_date
12,000          11/2014,11/2015
12,000          12/2014,12/2015

我想按月计算滚动成本,例如,如果你看11/14& 12/15是每月1000美元,而其余的是2000美元/月。我必须显示这个图表的信息。这可以在ruby或sql中完成。有人可以帮助逻辑,我需要的是某种数组

  [11/2014,1000],[12/2014,2000]...etc.

只需要一些逻辑帮助..

由于

1 个答案:

答案 0 :(得分:0)

以下是我在SQL Server中所做的事情:

declare @CostPeriod table
(
    AllocatedCost money not null
    ,StartDate date
    ,EndDate date
)

insert @CostPeriod
select 12000,'2014-11-01','2015-11-01'
union select 12000,'2014-12-01','2015-12-01'

declare @start date
, @stop date

select @start = MIN(startdate)
, @stop = MAX(enddate)
from @CostPeriod

select [Month]
, SUM(AllocatedCost / (DATEDIFF(month,startdate,enddate))) ValueThisMonth
from (select dateadd(month,n,@start) [Month] from dbo.generate_series(0, DATEDIFF(month,@start,@stop), 1, 0)) x
left outer join @CostPeriod on [Month] between StartDate and EndDate
group by [Month]
order by [Month]

使用此处的Generate_Series代码:https://developer42.wordpress.com/tag/generate_series/

现在可以转换到MySQL /很快就会回复 - 希望这会让你在等待的时候继续...