我的 table 是这样的
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.
只是需要一些逻辑方面的帮助..
谢谢
最佳答案
这是我在 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/很快就会发回来 - 希望这能为您在等待期间提供一些帮助...
关于mysql - 滚动月份的 Rails 或 sql 逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26982414/