根据存储过程中传递到临时文件中的月数将日期拆分为月份和年份 table

Split date into month and year based on number of months passed in stored procedure into a temp table

我有一个存储过程,其中将数字的数量作为参数。我用这样的 where 子句进行查询

select salesrepid, month(salesdate), year(salesdate), salespercentage 
from SalesRecords
where salesdate >= DATEADD(month, -@NumberOfMonths, getdate())

例如,如果@NumberOFmonths passed = 3 并且基于今天的日期,

它应该在我的结果集中带来 9 月 9 日、10 月 10 日和 11 月 11 日。我的查询带来了它,但请求是我需要 return null 对于一个月没有价值的销售人员,

例如:

salerepid     month      year     salespercentage
 232          9         2020       80%
 232          10        2020       null
 232          11        2020       90%

我怎样才能做到这一点?现在查询只带回两条记录并且不带十月数据,因为那里没有值,但我希望它为 return 十月空值。

如果我没听错的话,您可以生成目标间隔内的所有月份开始,并且 cross join 与 table 一起生成所有可能的组合。然后你可以把 table 和 left join:

with all_dates as (
    select datefromparts(year(getdate()), month(getdate()), 1) salesdate, 0 lvl
    union all
    select dateadd(month, - lvl - 1, salesdate), lvl + 1
    from all_dates 
    where lvl < @NumberOfMonths
)
select r.salesrepid, d.salesdate , s.salespercentage
from all_dates d
cross join (select distinct salesrepid from salesrecords) r
left join salesrecord s
    on  s.salesrepid = r.salesrepid
    and s.salesdate >= d.salesdate 
    and s.salesdate <  dateadd(month, 1, d.salesdate )

您的原始查询和结果暗示每个销售代表和每个月最多有一个记录,因此这在相同的假设下有效。如果不是这种情况(这在某种程度上更有意义),您将需要在外部查询中进行聚合。

声明@numberofmonths int = 3;

with all_dates as (
    select datefromparts(year(getdate()), month(getdate()), 1) dt, 0 lvl
    union all
    select dateadd(month, - lvl - 1, dt), lvl + 1
    from all_dates 
    where lvl < 3
)
select * from all_dates

This gives me following result:
2020-11-01  0
2020-10-01  1
2020-08-01  2
2020-05-01  3

I want only:
2020-11-01  0
2020-10-01  1
2020-09-01  2