为了获得本周开始和本周结束的时间戳,我会执行以下操作。
SET @currentTimestamp = DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE()); SET @currentDate = DATEADD(s, @currentTimestamp, '19700101'); SET @currentWeek = DATEPART(wk, @currentDate); SET @starter = 1451654325; SET @weekSize = 604800; SET @beginOfWeek = @starter + ((@weekSize) * (@currentWeek - 2)); SET @endOfWeek = @starter + ((@weekSize) * (@currentWeek - 1));
像...这样的查询的未来是必要的。
Submit_Date BETWEEN @beginOfWeek AND @endOfWeek
作为本周的一部分做某事。
我可以使代码更优雅和漂亮吗?
答案 0 :(得分:0)
您可以直接在BETWEEEN
条件中使用此子查询结果:
SELECT LastSunday, DATEADD(dd, -7, LastSunday) AS SundayBeforeThat
FROM (SELECT CAST(GETUTCDATE() - DATEPART(dw, GETUTCDATE()) + 1 AS DATE) AS LastSunday) A
CAST(... AS DATE)
截断时间部分; DATEPART(dw, GETUTCDATE()) + 1
上周日的费用; DATEADD(dd, -7, LastSunday)
,负数可以追溯一周。实际上,我可能INNER JOIN
此子查询ON Submit_Date < LastSunday AND Submit_Date >= SundayBeforeThat
来过滤目标查询:
...
INNER JOIN (
SELECT CAST(GETUTCDATE() - DATEPART(dw, GETUTCDATE()) + 1 AS DATE) AS LastSunday
) w
ON Submit_Date >= DATEADD(dd, -7, w.LastSunday)
AND Submit_Date < w.LastSunday