T-SQL 将最近 6 周的数据检索到上周六

T-SQL Retrieve Last 6 Weeks Data to the Previous Saturday

SELECT TOP 100 *
FROM FactSalesDetail
WHERE TradingDate >= DATEADD(ww, -6, (Select MAX([TradingDate]) From FactSalesDetail))
ORDER BY TradingDate 

任何人都可以建议我如何将上述 WHERE 子句从从我的事实 Table 中的最大日期检索最近 6 周的数据转换为最近 6 周到上周六的数据?

所以从今天开始就是 1 月 1 日星期六,然后从那之后 6 周?

使用当前工作日可以获得上周六。
如果您将@@DATEFIRST 带入等式,那么它就不会依赖于 DATEFIRST 设置。

SELECT TOP 100 *
FROM FactSalesDetail
WHERE TradingDate >= CONVERT(DATE, DATEADD(WEEK, -6, DATEADD(DAY, -(@@DATEFIRST+DATEPART(WEEKDAY,GETDATE()))%7, 
GETDATE())))
  AND TradingDate <= CONVERT(DATE, DATEADD(DAY, -(@@DATEFIRST+DATEPART(WEEKDAY,GETDATE()))%7, 
GETDATE()))
ORDER BY TradingDate

日期范围的测试代码段

SET DATEFIRST 7;

SELECT 
  datename(weekday, date_now) AS weekday_now, date_now
, datename(weekday, date1) AS wd1, date1
, datename(weekday, date2) AS wd2, date2 
FROM
(
    SELECT 
      CAST(GETDATE() AS DATE) AS date_now
    , CONVERT(DATE, DATEADD(WEEK, -6, DATEADD(DAY, -(@@DATEFIRST+DATEPART(WEEKDAY,GETDATE()))%7, 
GETDATE()))) AS date1
    , CONVERT(DATE, DATEADD(DAY, -(@@DATEFIRST+DATEPART(WEEKDAY,GETDATE()))%7, 
GETDATE())) AS date2
) q
weekday_now date_now wd1 date1 wd2 date2
Tuesday 2022-01-04 Saturday 2021-11-20 Saturday 2022-01-01

db<>fiddle here