简体   繁体   English

T-SQL获取日期

[英]T-SQL to get dates

I've SSRS sales report to which I need to pass the dates for previous month's start date and end date which I am able to pass using below code. 我有SSRS销售报告,我需要使用以下代码传递上个月的开始日期和结束日期的日期。 However, since the sales report has data from the past year(2014) I need to pass the dates for last year as well. 但是,由于销售报告包含去年(2014年)的数据,因此我也需要传递去年的日期。 The below code gives StartDate1 as 2015-02-01 and EndDate1 as 2015-02-28. 以下代码将StartDate1设置为2015-02-01,将EndDate1设置为2015-02-28。 I need to get the dates for past year like 2014-02-01 as StartDate2 and 2014-02-28 as EndDate2 我需要获取过去一年的日期,例如2014-02-01作为StartDate2和2014-02-28作为EndDate2

SELECT  DATEADD(MONTH, DATEDIFF(MONTH, '19000201', GETDATE()), '19000101') AS StartDate1,
    DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()), '18991231') AS EndDate1

Since last day of month can vary, the important thing is to get the first day of the current month this year. 由于月份的最后一天会有所不同,因此重要的是获取今年当前月份的第一天。 From that you can calculate the other three values. 由此可以计算出其他三个值。

You could do this easily with expressions in the parameters' default values instead. 您可以改为使用参数默认值中的表达式来轻松实现此目的。

Start of Month
=Today.AddDays(1-Today.Day)

End of Month
=Today.AddDays(1-Today.Day).AddMonths(1).AddDays(-1)

Start of Month Last Year
=Today.AddDays(1-Today.Day).AddYears(-1)

End of Month Last Year:
=Today.AddDays(1-Today.Day).AddYears(-1).AddMonths(1).AddDays(-1)

But if you really want to do it in SQL, you can. 但是,如果您真的想在SQL中执行此操作,则可以。 Note below I'm describing how to get the start of month and then just using placeholder variables for it in the other expressions for clarity. 请注意,下面我将描述如何获取月份的开始,然后为了清楚起见,仅在其他表达式中使用占位符变量。

--Start of Month
dateadd(month, datediff(month, 0, getdate()), 0)

--End of Month
dateadd(day, -1, dateadd(month, 1, @StartOfMonth))

--Start of Month Last Year
dateadd(year, -1, @StartOfMonth)

--End of Month Last Year
dateadd(day, -1, dateadd(month, 1, @StartOfMonthLastYear))

Those are the pieces. 这些是碎片。 Put them together into one giant, very hard to read select statement like so: 将它们放在一起,就像下面这样,很难阅读选择语句:

select
    dateadd(month, datediff(month, 0, getdate()), 0) StartDate1,
    dateadd(day, -1, dateadd(month, 1, dateadd(month, datediff(month, 0, getdate()), 0))) EndDate1,
    dateadd(year, -1, dateadd(month, datediff(month, 0, getdate()), 0)) StartDate2,
    dateadd(day, -1, dateadd(month, 1, dateadd(year, -1, dateadd(month, datediff(month, 0, getdate()), 0)))) EndDate2

Now you see why I recommend just using internal parameters that can leverage the .NET datetime class methods. 现在您知道为什么我建议仅使用可以利用.NET datetime类方法的内部参数了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM