获得最近5周的续航时间

时间:2015-09-30 10:04:41

标签: sql-server

我需要在五个单独的列表中加载过去五周的信息,无论日期是什么时候。所以本周,我需要在这之前的最后5周。下周,我需要在那之前的最后5周,包括这一个。如果这是有道理的并且不会让你感到困惑吗?

基本上是这样的:

..BETWEEN '2015-09-21' AND '2015-09-27'

必须替换为:

SELECT DATEADD(wk,DATEDIFF(wk,7,GETDATE()),0) AND DATEADD(wk,DATEDIFF(wk,7,GETDATE()),6)

这很好,第二周也一样:

SELECT DATEADD(wk,DATEDIFF(wk,14,GETDATE()),0) AND DATEADD(wk,DATEDIFF(wk,14,GETDATE()),6)
从那时起

但是,它不再起作用了。我得到的结果与手动添加日期的结果不同。

SELECT DATEADD(wk,DATEDIFF(wk,21,GETDATE()),0) AND DATEADD(wk,DATEDIFF(wk,21,GETDATE()),6)

我在代码中做错了吗?

2 个答案:

答案 0 :(得分:1)

我认为您可以使用类似的代码,而不是手动设置char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; !strcmp(packetBuffer, "turn on light")

number

请注意,DECLARE @TestDate AS DATETIME DECLARE @WeekNumber AS INTEGER -- previous 5 weeks SELECT @TestDate = GETDATE() SELECT @WeekNumber = -5 WHILE @WeekNumber < 0 BEGIN SELECT @TestDate, @WeekNumber, DATEADD(WEEK, DATEDIFF(WEEK, 0, DATEADD(WEEK, @WeekNumber, @TestDate)), 0) AS StartDate, DATEADD(WEEK, DATEDIFF(WEEK, 0, DATEADD(WEEK, @WeekNumber, @TestDate)), 6) AS EndDate SELECT @WeekNumber = @WeekNumber + 1 END -- previous 5 weeks from next wednesday SELECT @TestDate = DATEADD(DAY, 7, GETDATE()) SELECT @WeekNumber = -5 WHILE @WeekNumber < 0 BEGIN SELECT @TestDate, @WeekNumber, DATEADD(WEEK, DATEDIFF(WEEK, 0, DATEADD(WEEK, @WeekNumber, @TestDate)), 0) AS StartDate, DATEADD(WEEK, DATEDIFF(WEEK, 0, DATEADD(WEEK, @WeekNumber, @TestDate)), 6) AS EndDate SELECT @WeekNumber = @WeekNumber + 1 END 循环的内容不会发生变化。我使用相同的代码来提取有关两个不同日期的信息。

答案 1 :(得分:1)

如果您对BETWEEN数据类型使用datetime,则应在一周开始时添加 7 天以查找该周结束

DATEADD(wk,DATEDIFF(wk,21,GETDATE()),7)