获取最后x个日历周的第一天和第一天

时间:2015-12-28 12:30:43

标签: sql sql-server

我希望从今天开始过去8周(GETDATE()) 因此,所有8周的格式必须是dd / mm。 我试过这样的事情

select "start_of_week" = cast(datepart(dd,dateadd(week, datediff(week, 0, getdate()), 0)) as CHAR(2))+'/'+cast(datepart(mm,dateadd(week, datediff(week, 0, getdate()), 0)) as CHAR(2));

这只适用于本周,但如何将其置于查询中并返回curr-1,curr-2,... curr-7周。最终结果必须是表格,其中一个玩家有一些金额,每周格式为dd / mm

4 个答案:

答案 0 :(得分:1)

也许这么简单?

WITH EightNumbers(Nmbr) AS
(
          SELECT 0 
    UNION SELECT -1
    UNION SELECT -2
    UNION SELECT -3
    UNION SELECT -4
    UNION SELECT -5
    UNION SELECT -6
    UNION SELECT -7
    UNION SELECT -8
)
SELECT CONVERT(VARCHAR(5),GETDATE()+(Nmbr*7),103)
FROM EightNumbers
ORDER BY Nmbr DESC

如果您需要(如标题所示)"第一天"在本周,您可以将选择更改为:

SELECT CONVERT(VARCHAR(5),GETDATE()+(Nmbr*7)-DATEPART(dw,GETDATE())+@@DATEFIRST,103)
FROM EightNumbers
ORDER BY Nmbr DESC

请注意"一周的第一天"取决于你的系统文化。看看@@DATEFIRST

结果:

28/12
21/12
14/12
07/12
30/11
23/11
16/11
09/11
02/11

答案 1 :(得分:0)

语法: 选择“start_of_week”= cast(datepart(dd,dateadd(week,datediff(week,0,getdate()) - X ,0))为CHAR(2))

  select "start_of_week" = 
    cast(datepart(dd,dateadd(week, datediff(week, 0, getdate()) - 0, 0)) as CHAR(2)) ,
"previous_week1" = 
    +'/'+cast(datepart(mm,dateadd(week, datediff(week, 0, getdate()) - 1, 0)) as CHAR(2)),
"previous_week2" = 
    +'/'+cast(datepart(mm,dateadd(week, datediff(week, 0, getdate()) - 2, 0)) as CHAR(2)),
"previous_week3" = 
    +'/'+cast(datepart(mm,dateadd(week, datediff(week, 0, getdate()) - 3, 0)) as CHAR(2));

等等......谢谢

答案 2 :(得分:0)

你走了:

DECLARE @DateTable TABLE ( ADate DATETIME )
DECLARE @CurrentDate DATETIME

SET @CurrentDate = GETDATE()

WHILE (SELECT COUNT(*) FROM @DateTable WHERE DATEPART( dw, ADate ) = 2) <= 7
BEGIN
 INSERT INTO @DateTable
 SELECT @CurrentDate

 SET @CurrentDate = DATEADD( dd, -1, @CurrentDate )

END

SELECT "start_of_week" = cast(datepart(dd,dateadd(week, datediff(week, 0, ADate), 0)) as CHAR(2))
                        +'/'+cast(datepart(mm,dateadd(week, datediff(week, 0, ADate), 0)) as CHAR(2)) 
FROM @DateTable 
WHERE DATEPART( dw, ADate ) = 2

DELETE @DateTable

<强>输出

start_of_week
28/12
21/12
14/12
7 /12
30/11
23/11
16/11
9 /11

答案 3 :(得分:0)

假设sys.all_objects至少有8行而你想要一周的第一天(你没有在你的问题中指明:

select top 8 convert(varchar(5),
        dateadd(WEEK,
                1-1* ROW_NUMBER() over(order by newid()),
                 dateadd(DD,
                            1-datepart(dw,getdate()),
                            getdate())),
        1) as [FirstDayOfWeek]
  from sys.all_objects

转换只是给出月/日。行号用于给出数字1-8。我将行数乘以-1并加1以得到数字0,-1,-2,... - 7和日期将这些(按日)添加到本周的第一天。我发现本周的第一天采用了getdate和date添加了星期几的负面版本+ 1.