T-SQL如何从GetDate()的所有季度获得第一周的周数(ISO)?

时间:2017-10-05 21:18:33

标签: sql sql-server function date

标题说得很多。

但更准确地说,我需要从GetDate()获得任何给定年份的第1-4季度的每周周数。

不确定这是内置的还是我必须为其编写函数。

谢谢!

1 个答案:

答案 0 :(得分:2)

这很简单,但可以解决问题。您可以将@date设置为任何给定值。我使用了getdate()

declare @date datetime = getdate()

declare @year int = datepart(year, @date)

select @year as [year]
      ,datepart(iso_week, cast('1/1/'  + cast(@year as char(4)) as date)) as ISOWeekQ1
      ,datepart(iso_week, cast('4/1/'  + cast(@year as char(4)) as date)) as ISOWeekQ2
      ,datepart(iso_week, cast('7/1/'  + cast(@year as char(4)) as date)) as ISOWeekQ3
      ,datepart(iso_week, cast('10/1/' + cast(@year as char(4)) as date)) as ISOWeekQ4

对我来说,这回来了:

year        ISOWeekQ1   ISOWeekQ2   ISOWeekQ3   ISOWeekQ4
----------- ----------- ----------- ----------- -----------
2017        52          13          26          39

这也有效,并且不会对日期的不同格式使用cast()或冒险日期转换错误(例如,yyyy / mm / dd):

declare @date datetime = getdate()

set @date = dateadd(day, - datepart(dayofyear, @date) + 1, @date) -- sets date to Jan 1

select datepart(year, @date) [year]
      ,datepart(iso_week, @date) as ISOWeekQ1
      ,datepart(iso_week, dateadd(month, 3, @date)) as ISOWeekQ2
      ,datepart(iso_week, dateadd(month, 6, @date)) as ISOWeekQ3
      ,datepart(iso_week, dateadd(month, 9, @date)) as ISOWeekQ4

此查询的输出与第一个查询的输出相同。