我有一个名为Actuals_Date的列,我希望在滚动的基础上将日期插入表中,以便将前6周和接下来的8周加载到表中。
在过去的6周内,我有以下sql结构(来自Tableau)
[Actuals Date] > DATEADD('week',-6,DATETRUNC('week', TODAY()) - 1) and [Actuals Date] <= DATETRUNC('week', TODAY()) - 1
以及接下来的8周,遵循Tableau的语法:
[Forecast Date] >= DATETRUNC('week', TODAY()) - 1
and [Forecast Date] <= DATEADD('week', 7,DATETRUNC('week', TODAY()) - 1)
有人可以帮我转换成sql查询吗?
答案 0 :(得分:1)
实现目标的一种方法是使用DATEADD()
过去6周:
SELECT f.MyColumns
FROM dbo.MyTable f
WHERE f.MyDateField BETWEEN DATEADD(WEEK,-6,CAST(GETDATE() AS DATE)) AND CAST(GETDATE() AS DATE)
接下来的8周:
SELECT f.MyColumns
FROM dbo.MyTable f
WHERE f.MyDateField BETWEEN CAST(GETDATE() AS DATE) AND DATEADD(WEEK,8,CAST(GETDATE() AS DATE))
注意:这假定f.MyDateField是没有时间的日期。如果f.MyDateField有时间,您将希望将其作为DATE
进行CASTSELECT f.MyColumns
FROM dbo.MyTable f
WHERE CAST(f.MyDateField AS DATE) BETWEEN DATEADD(WEEK,-6,CAST(GETDATE() AS DATE)) AND CAST(GETDATE() AS DATE)