1

我有一个表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

我真的很感激任何帮助,因为我被困在这一点上并且无法弄清楚这一点。

4

1 回答 1

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).

或者,您可以在您的应用程序中构建一个月度日历表,并直接使用该表执行几乎相同的操作。

于 2020-01-26T12:20:00.813 回答