SQL会提取本年度的数据,直到上周五(星期五)

时间:2019-03-19 23:01:13

标签: sql sql-server datetime

我正试图从 datetime 字段 fetchDate

中获取本年度前周五的SQL数据。

我尝试了类似的方法,但直到今天才获取

(year(fetchDate) = year(GETDATE()) and month(fetchDate) <= month(GETDATE()) and day(fetchDate) <= day(GETDATE()))

(year(fetchDate) = year(GETDATE()) and month(fetchDate) <= month(GETDATE()) and day(fetchDate) <= day(DATEADD(wk,DATEDIFF(wk,7,GETDATE()),4)))

仅为我提供一年中当前月份到上周的数据。

2 个答案:

答案 0 :(得分:1)

我相信您需要的是以下物品:

WHERE YEAR(fetchDate) = YEAR(CURDATE()) 
AND fetchDate < DATE_SUB(NOW(), INTERVAL ((7 + WEEKDAY(DATE_SUB(NOW(), INTERVAL 1 WEEK)) - 4) % 7) DAY)

我们知道上周的星期五是多少天前:

((7 + WEEKDAY(DATE_SUB(NOW(), INTERVAL 1 WEEK)) - 4) % 7)

答案 1 :(得分:1)

我宁愿采用以下解决方案,因为它是可安装的。在WHERE谓词内部,我们没有将fetchdate包装到函数中(例如YEAR(Fetchdate)),查询优化器可以使用现有索引,而不必扫描整个表。特别是对于查询比较普遍的BI工作负载而言,优化查询大量记录非常重要。它以可读性

为代价
declare @tab table
(
    fetchdate datetime
)
insert into @tab
values ('2019-01-01'),('2019-03-15'),('2018-12-31'),('2019-03-16')
SELECT 
*,
case when datepart(weekday, getdate()) >5 then
 DATEADD(DAY, +4, DATEADD(WEEK, DATEDIFF(WEEK, 0, getdate()), 0)) 
else DATEADD(DAY, -3, DATEADD(WEEK, DATEDIFF(WEEK, 0, getdate()), 0)) end as TestLastFriday,
DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) as TestFirstDayOfYear
FROM @tab
where 
    fetchdate <= case when datepart(weekday, getdate()) >5 then DATEADD(DAY, +4, DATEADD(WEEK, DATEDIFF(WEEK, 0, getdate()), 0)) 
                 else DATEADD(DAY, -3, DATEADD(WEEK, DATEDIFF(WEEK, 0, getdate()), 0)) end and 
    fetchdate >= DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)