SQL,列出具有每周的周数和周一日期的x记录

时间:2013-12-03 14:27:18

标签: sql

我正在寻找一个SQL查询,它会为我提供周末数和周一特定周的日期列表。

例如:

WeekNumber  DateMonday
39          2013-09-23
40          2013-09-30
...         ...

以下justs产生一周

select
     (DATEPART(ISO_WEEK,(CAST(getdate() as DATETIME)))) as WeekNumber,
     DATEADD(wk, DATEDIFF(d, 0, CAST(getdate() as DATETIME)) / 7, 0) AS DateMonday

1 个答案:

答案 0 :(得分:1)

如果您没有数字表,您可以使用系统表动态生成连续数字列表:

e.g

SELECT  Number = ROW_NUMBER() OVER(ORDER BY object_id)
FROM    sys.all_objects;

如果您需要扩展此数字以获得更多数字,您可以使用CROSS JOIN表:

SELECT  Number = ROW_NUMBER() OVER(ORDER BY a.object_id)
FROM    sys.all_objects a
        CROSS JOIN sys.all_objects b;

然后您只需要在开始日期之前添加/减去这些周数:

DECLARE @Monday DATE = DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0);

WITH Numbers AS
(   SELECT  Number = ROW_NUMBER() OVER(ORDER BY object_id)
    FROM    sys.all_objects
)
SELECT  WeekNumber = DATEPART(ISO_WEEK, w.DateMonday),
        w.DateMonday
FROM    (   SELECT  DateMonday = DATEADD(WEEK, - n.Number, @Monday)
            FROM    Numbers n
        ) w;

这是一种逐步清晰的冗长方式,可以简化为:

SELECT  WeekNumber = DATEPART(ISO_WEEK, w.DateMonday),
        w.DateMonday
FROM    (   SELECT  DateMonday = DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()) - ROW_NUMBER() OVER(ORDER BY object_id), 0)
            FROM    sys.all_objects
        ) w;

<强> Example on SQL Fiddle

Aaron Bertrand已经深入比较了生成连续数字列表的方法:

当然,最简单的方法是创建calendar table