我有一个表ClientProfile
,其中包含名为StartDate
的列,此列的数据类型为date
,第二列称为MonthlyRevenue
,这是numeric(18,2)
中的金额列,第三列为称为ContractMonths
数据类型int
,它指定项目将处于活动状态的月数。用户需要选择一个日期范围,并且查询应该能够获取完整的日期范围(逐月),指定每个月的金额。
例如:项目A将从2020-03-01
(1st March
)开始,合同将运行6个月,因此当用户选择日期02-2020
至12-2020
时。
我应该能够得到这样的结果:
Month Revenue
-----------------
02-2020 0
03-2020 100
04-2020 100
05-2020 100
06-2020 100
07-2020 100
08-2020 100
09-2020 0
10-2020 0
11-2020 0
12-2020 0
我将非常感谢您的帮助,因为我被困在这一点上并且无法解决。
一种方法是生成月份的递归CTE:
with months as (
select @startmonth as mon
union all
select dateadd(month, 1, mon)
from months
where mon < @endmonth
)
select months.mon, coalesce(cp.monthlyrevenue, 0) as revenue
from months left join
clientprofile cp
on cp.project = @project and
cp.startdate <= months.mon and
dateadd(month, cp.contractmonths, cp.startdate) >= months.mon;
如果期限超过100个月,则需要添加option (maxrecursion 0)
。
或者,您可以在应用程序中构建每月日历表,并直接使用该表执行几乎相同的操作。