获取本周开始和一周结束的时间戳

时间:2016-10-31 20:12:32

标签: sql sql-server tsql

为了获得本周开始和本周结束的时间戳,我会执行以下操作。


    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

作为本周的一部分做某事。

我可以使代码更优雅和漂亮吗?

1 个答案:

答案 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