【问题标题】:Subtract month from varchar year and date parameter format '2016-11'从 varchar 年份和日期参数格式 '2016-11' 中减去月份
【发布时间】:2017-02-15 00:00:26
【问题描述】:

我有一个包含报告年和报告月列的表。对于报告年,该列是一个 vharchar (4),等于 2016 年格式。对于 reportmonth,它是具有 01、02、03 等格式的 varchar (2)。我有一个将两者连接起来的数据参数,因为我们的最终用户想要一个下拉日期。所以我的参数是@ReportDate varchar (7)。

我的问题是我的存储过程中的一个选择,我需要在它返回一个月的地方放置一个 where 子句。因此,如果我的参数等于“2016-11”,我想要一个返回“2016-10”的 where 子句。我已经使用流动查询成功地做到了这一点:

SUBSTRING(@Reportdate, 1, 4) + '-' + cast(substring(@ReportDate, 6, 7)  -1 as varchar(20))

如果我选择“2016-11”作为任何报告日期参数,这将返回“2016-10”。 但经过进一步思考,如果我的报告日期是在一月份,这将不起作用,因为上述查询只是从字面上减去一个字符串值。因此,如果我选择“2016-01”,上述查询将返回“2016-0”。

【问题讨论】:

    标签: sql sql-server sql-server-2008 tsql ssms


    【解决方案1】:

    例如:

    Declare @Reportdate varchar(7) = '2016-01'
    
    Select AsDate  = dateadd(MM,-1,@ReportDate+'-01')
          ,AsSting = left(convert(date,dateadd(MM,-1,@ReportDate+'-01'),101),7)
    

    返回

    AsDate      AsSting
    2015-12-01  2015-12
    

    【讨论】:

    • 最终用户希望 SSRS 中的下拉参数带有破折号,这就是为什么我将其声明为 varchar(7) 以包含破折号 @John Cappelletti
    • @Lisbon 当我看到评论时,我更新为包含破折号。 varchar(7) vs varchar(10) 没有问题
    【解决方案2】:

    你可以使用case:

    select concat(@ReportYear - 1,
                  (case when @ReportMonth = '01' then '12'
                        else right(concat('0', @ReportMonth - 1))
                   end)
                 )
    

    SQL Server 会将字符串视为整数——您的值不会出现转换错误。 concat() 然后将它们转换回字符串。

    编辑:

    我明白了,这是倒退。让我们在表中的列中加一并与@Report_Month进行比较:

    where (reportmonth = 12 and
           right(@ReportDate, 2) = '01' and left(@Report_date, 4) = reportyear + 1
          ) or
          (left(@ReportDate, 4) = reportyear and
           right(@ReportDate, 2) = reportmonth + 1
          )
    

    但考虑到这一点,我认为你应该使用计算列:

    alter table t add reportdate as ( datefromparts(reportyear, reportmonth, 1) );
    

    然后简单地做:

    where dateadd(month, 1, reportdate) = cast(@reportdate + '01' as date)
    

    当然,你可以做显式比较:

    where (dateadd(month, 1, datefromparts(reportyear, reportmonth, 1)) =
           cast(@reportdate + '01' as date)
          )
    

    请注意,这两个都假定@reportdate 是一个字符串。

    【讨论】:

    • 我的参数是 atReportDate,它是 Reportyear 和 reportmonth 列的串联。所以在我的 where 子句中,我有它: where reportyear + '-' + reportmonth = @ReportDate (ReportDate being '2016-11')
    猜你喜欢
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    相关资源
    最近更新 更多