我有一个代码,过去几个月一直用来获取数据,但是当新年到来时,我意识到它没有填充任何数据,因为它没有正确计算周数。
我将代码编写为 week - 4,但它没有提供 2023 年 12 月最后几周的任何数据。有人可以帮我弄清楚如何编辑代码,以便它给我最后几周的数据。 我假设这是因为当前周是 1 并且 1 - 4 = -3 不存在。
Select id,
EXTRACT(WEEK FROM transaction_date) as week
from table1
where week BETWEEN DATEPART(WEEK, GETDATE())-4 AND DATEPART(WEEK, GETDATE())
使用日历表可以更轻松地解决此类挑战。
当您仅使用实际日期而不是其中的一部分时,这将成为一项更加简单的任务。考虑:
假设 OP 使用 DATEPART 的 TSQL/SQL Server
SELECT
CAST(DATEADD(WEEK,-4,DATEADD(DAY,1-DATEPART(WEEKDAY,GETDATE()),GETDATE())) AS DATE) AS RangeStart,
DATEADD(MILLISECOND,-3,CAST(DATEADD(DAY,7,CAST(DATEADD(WEEK,-4,DATEADD(DAY,1-DATEPART(WEEKDAY,GETDATE()),GETDATE())) AS DATE)) AS DATETIME)) AS RangeEnd;
范围开始 | 范围结束 |
---|---|
2023-12-03 | 2023-12-09 23:59:59.997 |
DECLARE @RangeStart DATETIME = CAST(DATEADD(WEEK,-4,DATEADD(DAY,1-DATEPART(WEEKDAY,GETDATE()),GETDATE())) AS DATE) AS RangeStart,
@RangeEnd DATETIME = DATEADD(MILLISECOND,-3,CAST(DATEADD(DAY,7,CAST(DATEADD(WEEK,-4,DATEADD(DAY,1-DATEPART(WEEKDAY,GETDATE()),GETDATE())) AS DATE)) AS DATETIME)) AS RangeEnd
SELECT t.id, DATEPART(WEEK,t.transaction_date) AS week
FROM table1 t
WHERE t.transaction_date BETWEEN @RangeStart AND @RangeEnd;