SQL - 从机器选择当前日期并比较一年 [英] SQL - pick current date from machine and compare the year
本文介绍了SQL - 从机器选择当前日期并比较一年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
情景1:当前年份
始终代码需要选择
今年1月份的最后一个星期日。对于ex(31-01-2016)
The last Sunday of January for the current year. For ex(31-01-2016)
当前代码 - 选择2016年1月1日
convert(date,DATEADD(yy, DATEDIFF(yy, 0, getdate()), 0))
情景2:去年
代码需要选择
上一年1月的最后一个星期日。对于ex(01-02-2015)
The last Sunday of January for the Previous year. For ex(01-02-2015)
当前代码 - 选择2015年1月1日
convert(date,DATEADD(yy, DATEDIFF(yy, 0, dateadd(YEAR, - 1, getdate())), 0))
而不是硬编码日期。我想从机器上选择日期并进行比较。
Instead of hard coding the date. I would like to pick date from machine and compare.
星期天从周六开始,星期六结束。任何帮助?
推荐答案
-- Sample Demonstrative Data/Test Results
Declare @YourTable table (SomeDate date)
Insert Into @YourTable values ('2000-06-15'),('2001-06-15'),('2002-06-15'),('2003-06-15'),('2004-06-15'),('2005-06-15'),('2006-06-15')
,('2007-06-15'),('2008-06-15'),('2009-06-15'),('2011-06-15'),('2012-06-15'),('2013-06-15'),('2014-06-15'),('2015-06-15'),('2016-06-15')
,('2017-06-15'),('2018-06-15'),('2019-06-15'),('2020-06-15')
-- To Confirm Results
Select Year = year(SomeDate)
,LastSundayDate = DateAdd(DD,-DatePart(DW,DateFromParts(Year(SomeDate),12,31))+1,DateFromParts(Year(SomeDate),12,31))
,LastSundayName = DateName(DW,DateAdd(DD,-DatePart(DW,DateFromParts(Year(SomeDate),12,31))+1,DateFromParts(Year(SomeDate),12,31)))
From @YourTable
Re转到
Year LastSundayDate LastSundayName
2000 2000-12-31 Sunday
2001 2001-12-30 Sunday
2002 2002-12-29 Sunday
2003 2003-12-28 Sunday
2004 2004-12-26 Sunday
2005 2005-12-25 Sunday
2006 2006-12-31 Sunday
2007 2007-12-30 Sunday
2008 2008-12-28 Sunday
2009 2009-12-27 Sunday
2011 2011-12-25 Sunday
2012 2012-12-30 Sunday
2013 2013-12-29 Sunday
2014 2014-12-28 Sunday
2015 2015-12-27 Sunday
2016 2016-12-25 Sunday
2017 2017-12-31 Sunday
2018 2018-12-30 Sunday
2019 2019-12-29 Sunday
2020 2020-12-27 Sunday
这篇关于SQL - 从机器选择当前日期并比较一年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文