【发布时间】:2022-02-07 09:01:48
【问题描述】:
想要编写一个查询,只列出当天晚上 8 点到 11:59 之间插入的记录。
注意:uploaddate 字段包含日期和时间。因此,该记录可以提前几天或几天后插入。我有兴趣仅过滤当天晚上 8 点到 11.59 之间插入的记录。
上传时间在字段上传日期中可用。我可以在一天内完成,也可以使用 R/Python 代码在多天内完成。
在上面的例子中,只有突出显示的记录应该被包括在内,其余的应该被排除。
查询以列出一天。
select *
from dbo.table
where t = '20220204'
and uploaddate between '2022-02-04 20:00:00' and '2022-02-04 23:59:00'
and uploaddate is not null
order by uploaddate desc
要列出多天的 R 代码
thisDate = Sys.Date()
currentDate = as.Date('2021-01-01', format("%Y-%m-%d"))
allRows = NULL
while ( currentDate < thisDate) {
if ( format(currentDate, "%u") < 6 ) {
thisDateStr = as.numeric(format(currentDate,"%Y"))*10000+as.numeric(format(currentDate,"%m"))*100+as.numeric(format(currentDate,"%d"))
uploadDateStart = paste0(format(currentDate, format = "%Y-%m-%d") , " 20:00:00", sep="")
uploadDateEnd= paste0(format(currentDate, format = "%Y-%m-%d") , " 23:59:00", sep="")
query = paste0("select * from dbo.table where t = '", thisDateStr,"' and uploaddate is not null and uploaddate between '", uploadDateStart, "' and '", uploadDateEnd , "' order by uploaddate desc ", sep="")
rowsToAdd =sqlQuery(dbhandle_prod,daily_market_data_query)
if ( nrow(daily_market_data_results) > 0 ) {
allRows = rbind(allRows, rowsToAdd )
}
}
currentDate = currentDate + 1
}
想知道是否可以在 SQL Server 中完成,而无需编写 R/Python 代码。
【问题讨论】:
-
你给我们样本数据和预期结果怎么样?
-
根据问题指南,请不要发布代码、数据、错误消息等的图像 - 将文本复制或输入到问题中。请保留将图像用于图表或演示渲染错误,无法通过文本准确描述的事情。
-
那么您现有的查询有什么问题,它似乎可以满足您的需求?旁白:排除
23:59:00和午夜之间的任何内容似乎很愚蠢,您可能想做and uploaddate >= '2022-02-04 20:00:00' and uploaddate < '2022-02-05 00:00:00' -
@nsivakr 但您的问题和示例数据仅指一天?我一直试图在上面的多个 cmets 中向您说明这一点。请确保您的问题是明确的,并且您的示例数据完全代表您感兴趣的场景。
-
因此,如果您要解决的问题是多日问题,请提供示例数据和所需结果。您的问题非常令人困惑,因为您主要谈论的是单日,但似乎您想解决多日。然后检查 SQL Server 日期时间函数以获取灵感。
标签: sql sql-server datetime