获得去年的最后一天

时间:2015-12-04 09:51:36

标签: sql-server tsql date

任何人都可以帮助我获得去年的最后一天我有3个案例:
如果startdate = 04-12-2015和此日期的日期介于1 - > 10之间    得到startdate =01-01-2015endDate = 30-11-2015

如果startdate = 12-12-2015和此日期的日期不在1 - > 10之间    得到startdate =01-01-2015endDate = 12-12-2015

如果startdate = 04-01-2016和此日期的日期介于1 - > 10之间    得到startdate =01-01-2015endDate = 31-12-2015

更新:有新案例: 如果startdate = 12-12-2016和此日期的日期不在1 - > 10之间    得到startdate =01-01-2015endDate = 12-12-2015所以我在这种情况下需要帮助

 DECLARE        @endDate      Date 
DECLARE     @startDate    Date   
SET         @startDate = '2016/12/12'   --'2016/01/04' GETDATE() '2015/12/12'
--Check if startDate are between January and October
    IF (FORMAT(@startDate,'dd') between 01 AND 10 )  AND ( YEAR(@startDate) <> YEAR(GETDATE()) )
       BEGIN
            PRINT 'IF loop <> year'
            SET   @endDate   = CONVERT(varchar,dateadd(ms,-2,dateadd(year,0,dateadd(year,datediff(year,0,@startDate),0))),106) 
            SET   @startDate = CONVERT(varchar,dateadd(year,datediff(year,0,@endDate),0),106)
            PRINT @endDate 
            PRINT @startDate
       END

    ELSE IF FORMAT(@startDate,'dd') between 01 AND 10 
       BEGIN
            PRINT 'IF loop current year'
            SET   @endDate   = CONVERT(varchar,dateadd(d,-(day(getdate())),getdate()),106) 
            SET   @startDate = CONVERT(varchar,dateadd(year,datediff(year,0,@endDate),0),106)
            PRINT @endDate 
            PRINT @startDate
       END
    ELSE IF ( FORMAT(@startDate,'dd') not between 01 AND 10 ) AND ( YEAR(@startDate) <> YEAR(GETDATE()) )
       BEGIN
            PRINT 'ILSE loop not current year'
            SET   @endDate   = @startDate 
            SET   @startDate = CONVERT(varchar,dateadd(year,datediff(year,0,@endDate),0),106)
            PRINT @endDate 
            PRINT @startDate
       END
    ELSE 
       BEGIN
            PRINT 'ILSE loop  current year'
            SET   @endDate   = @startDate 
            SET   @startDate = CONVERT(varchar,dateadd(year,datediff(year,0,@endDate),0),106)
            PRINT @endDate 
            PRINT @startDate
       END

0 个答案:

没有答案