我有一个存储过程,其中将数字数量作为参数。我用这样的where子句查询
select salesrepid, month(salesdate), year(salesdate), salespercentage
from SalesRecords
where salesdate >= DATEADD(month, -@NumberOfMonths, getdate())
因此,例如,如果@NumberOFmonths通过= 3并基于今天的日期,
它应该在我的结果集中显示9月9日,10月10日和11月11日。我的查询带来了它,但是请求是我需要为那些没有一个月的值的salesrep返回null,
例如:
salerepid month year salespercentage
232 9 2020 80%
232 10 2020 null
232 11 2020 90%
我怎样才能做到这一点?现在查询只带回两个记录,并且不带10月数据,因为那里没有值,但是我希望它返回具有空值的10月。
如果我正确地遵循了您的规定,您可以在目标间隔内生成所有月份的开始时间,并cross join
可以通过表格生成所有可能的月份。然后,您可以在桌子上摆一个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 )
您的原始查询和结果暗示每个销售代表和每个月最多有一条记录,因此在相同的假设下也可以使用。如果不是这种情况(从某种意义上讲更有意义),则需要在外部查询中进行聚合。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句