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

How to calculate the no of iso weeks in a year in t-sql?

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

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

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);

或更好...因为我们正在计算静态值,为什么不将这些值弹出到 table 然后像这样索引它:

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 周数,您都可以通过索引搜索从 table 中检索预先计算的值。

SELECT * FROM dbo.ISOCounts WHERE yr = 2014;

结果:

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