【问题标题】:Split date into month and year based on number of months passed in stored procedure into a temp table根据在存储过程中传递到临时表中的月数将日期拆分为月份和年份
【发布时间】:2020-11-19 00:21:58
【问题描述】:

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

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

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

它应该在我的结果集中带来 9 月 9 日、10 月 10 日和 11 月 11 日。我的查询带来了它,但请求是我需要为那些一个月内没有值的销售代表返回 null,

例如:

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

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

【问题讨论】:

    标签: sql sql-server datetime where-clause recursive-query


    【解决方案1】:

    如果我正确地跟随你,你可以在目标间隔内生成所有月份的开始,并且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 )
    

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

    【讨论】:

    • 你说得对,在我的 salesrepid 和 salesdate 查询中有一个 group by
    • @KarthikDooty:好的,所以你应该在上面的查询中有一个group by r.salesrepid, d.salesdate - 并在s.salespercentage上使用某种聚合函数。
    【解决方案2】:

    声明@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
    

    【讨论】:

    • 加上它也没有给我任何空记录。只有匹配的记录来自查询,感谢回复
    猜你喜欢
    • 2012-03-03
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    相关资源
    最近更新 更多