如何计算t-sql中一年中的iso周数?

时间:2016-12-28 14:55:09

标签: tsql iso

我需要一个简单的查询来计算任何给定年份的iso周数?

1 个答案:

答案 0 :(得分:2)

我认为这应该可以解决问题。

DECLARE @year smallint = 2015;

SELECT 
  TheYear = @year,
  ISOWeeks= MAX(DATEPART(ISOWK,DATEADD(DD,N,CAST(CAST(@year AS char(4))+'1223' AS date))))
FROM (VALUES (1),(2),(3),(4),(5),(6),(7),(8)) t(N);

您可以将此逻辑包含在以下函数中:

CREATE FUNCTION dbo.CalculateISOWeeks(@year smallint)
RETURNS TABLE WITH SCHEMABINDING AS RETURN
SELECT ISOWeeks = 
  MAX(DATEPART(ISOWK,DATEADD(DD,N,CAST(CAST(@year AS char(4))+'1223' AS date))))
FROM (VALUES (1),(2),(3),(4),(5),(6),(7),(8)) t(N);

并像这样使用它:

SELECT ISOWeeks FROM dbo.CalculateISOWeeks(2014);

或更好......因为我们正在计算静态值,为什么不将这些值弹出到表中然后将其索引如下:

SELECT 
  Yr       = ISNULL(CAST(Yr AS smallint),0), 
  ISOWeeks = ISNULL(CAST(ISOWeeks AS tinyint),0)
INTO dbo.ISOCounts
FROM
(
  SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL))+1949
  FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) a(x),
       (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) b(x)
) Years(Yr)
CROSS APPLY dbo.CalculateISOWeeks(Yr+1950);

CREATE UNIQUE CLUSTERED INDEX uci_ISOCounts ON dbo.ISOCounts(Yr);

现在,无论何时需要计算给定年份的ISO周数,您都可以通过索引搜索从表中检索预先计算的值。

SELECT * FROM dbo.ISOCounts WHERE yr = 2014;

结果:

Yr     ISOWeeks
------ --------
2014   53