如何从每日数据中 select 每周数据

How to select weekly data from daily data

有两列,XCHG_DATE 和 USD_KRW,table 包含每日数据。

我想做的是 select 从每日数据中提取每周数据。

例如) (2022-03-01, value), (2022-03-08, value), (2022-03-15, value), (2022-03-22, value) 等等。 ..

我现在的SQL是:

SELECT CE.XCHG_DATE xchageDate
    ,  CE.USD_KRW usdKrw
    FROM(
        SELECT DATEADD(WEEK, DATEDIFF(WEEK, 1, XCHG_DATE), 4) xchageDate
        FROM CWL_EXCHANGE 
        WHERE XCHG_DATE BETWEEN '20220301' AND '20220523' 
        GROUP BY DATEADD(WEEK, DATEDIFF(WEEK, 1, XCHG_DATE),4)
    ) AS RESULT
LEFT JOIN CWL_EXCHANGE CE
ON CE.XCHG_DATE = RESULT.xchageDate
WHERE RESULT.xchageDate = CE.XCHG_DATE
ORDER BY CE.XCHG_DATE;

此查询为我提供了从 20220304 到 20220520 的每周数据,但我需要从 2022-03 到 2022-05-23(今天的日期)的数据。

谁能帮我解决这个问题? 提前致谢!


示例数据:

COLUMNS = XCHG_DATE    USD_KRW
          2022-05-23   1
          2022-05-22   2
          2022-05-21   3
          2022-05-20   4
          2022-05-19   5
          2022-05-18   6
          2022-05-17   7
          2022-05-16   8
          2022-05-15   9
          2022-05-14   10
          2022-05-13   11          
          2022-05-12   12
          2022-05-11   13
          2022-05-10   14
          2022-05-09   15
          2022-05-08   16
          2022-05-07   17
          2022-05-06   18

当前输出:

20220506  18
20220513  11
20220520  4

预期输出:

20220509  15  
20220516  8  
20220523  1

如果您总是想要今天的日期,请在 GETDATE() 中订阅硬编码值

SELECT * 
FROM CWL_EXCHANGE  
WHERE DATEPART(dw, XCHG_DATE) = DATEPART(dw, '20220523')

您将需要一个带有工作日编号的日历 table 才能到达与今天的日期(2022 年 5 月 23 日)相对应的较早的工作日。这将使计算更容易。

DECLARE @StartDate DATE = '2022-05-01'
DECLARE @EndDate DATE = '2022-05-31'
declare @table table (XCHG_DATE    date, USD_KRW int);
insert into @table 
values ('2022-05-23', 1  )
          ,('2022-05-22', 2  )
          ,('2022-05-21', 3  )
          ,('2022-05-20', 4  )
          ,('2022-05-19', 5  )
          ,('2022-05-18', 6  )
          ,('2022-05-17', 7  )
          ,('2022-05-16', 8  )
          ,('2022-05-15', 9  )
          ,('2022-05-14', 10 )
          ,('2022-05-13', 11 )         
          ,('2022-05-12', 12 )
          ,('2022-05-11', 13 )
          ,('2022-05-10', 14 )
          ,('2022-05-09', 15 )
          ,('2022-05-08', 16 )
          ,('2022-05-07', 17 )
          ,('2022-05-06', 18 );
;WITH Cal(n) AS
(
SELECT 0 UNION ALL SELECT n + 1 FROM Cal
WHERE n < DATEDIFF(DAY, @StartDate, @EndDate)
),
FnlDt(d,weeknum) AS
(
SELECT DATEADD(DAY, n, @StartDate),datepart(dw, DATEADD(DAY, n, @StartDate)) as weeknum FROM Cal
)
SELECT t.XCHG_DATE,t.USD_KRW 
from FnlDt as c
INNER JOIN @table as t
on t.XCHG_DATE = c.d
where c.weeknum = datepart(dw, getdate()) -- Weekdaynumber today 
XCHG_DATE USD_KRW
2022-05-23 1
2022-05-16 8
2022-05-09 15