我正在尝试使用 SQL 查询搜索一个相当大的(56m+ 行(表。能够像这样进行一些快速SQL查询的复杂性:
Select *COLUMNS*
From *Table*
Where *Conditions* And
LOG_ENTRY_TIMESTAMP between {StartDate} and {EndDate}
是我需要从 {StartDate} 的前一天提取 23:00 - 24:00 小时,而不从该日期提取其余数据。{开始日期} 和 {结束日期} 是用户输入的日期格式字段。LOG_ENTRY_TIMESTAMP 是时间戳数据类型。
有没有比做这样的事情更省时的方法:
TRUNC(CAST(LOG_ENTRY_TIMESTAMP AS DATE), 'HH') BETWEEN {StartDate}-1/24 and {EndDate}+23/24
数据将如下所示:
ITEM LOG_ENTRY_TIMESTAMP
---- ----------------------------------
A 2/12/2018 10:02:19.214528 AM -0500
B 2/14/2018 11:02:19.224528 PM -0500
C 2/16/2018 01:02:19.412528 AM -0500
D 2/16/2018 11:02:19.412528 PM -0500
如果我从 {StartDate} = 2/15/2018到 {EndDate} = 2/16/2018 进行搜索,我想捕获 B & C。
我建议:
Where *Conditions* And
LOG_ENTRY_TIMESTAMP between {StartDate} - 1/24 and {EndDate}
我需要从前一天晚上 11 点到今晚 11 点的数据
如果我从 {StartDate} = 2/15/2018到 {EndDate} = 2/16/2018 进行搜索,我想捕获 B & C。
假设LOG_ENTRY_TIMESTAMP
已编入索引,您可以通过以下方式使用它:
Where *Conditions* And
LOG_ENTRY_TIMESTAMP >= {StartDate} - 1/24 and
LOG_ENTRY_TIMESTAMP < {EndDate} + 23/24
同样假设变量实际上是时间设置为午夜的日期,{StartDate} - 1/24
给出该开始日期前一天的 23:00,{EndDate} + 23/24
给出结束日期的 23:00。
将示例数据放在 CTE 中,并将筛选日期作为日期文本:
with your_table (item, log_entry_timestamp) as (
select 'A', to_timestamp_tz('2/12/2018 10:02:19.214528 AM -0500',
'MM/DD/YYYY HH:MI:SS.FF6 AM TZHTZM') from dual
union all select 'B', to_timestamp_tz('2/14/2018 11:02:19.224528 PM -0500',
'MM/DD/YYYY HH:MI:SS.FF6 AM TZHTZM') from dual
union all select 'C', to_timestamp_tz('2/16/2018 01:02:19.412528 AM -0500',
'MM/DD/YYYY HH:MI:SS.FF6 AM TZHTZM') from dual
union all select 'D', to_timestamp_tz('2/16/2018 11:02:19.412528 PM -0500',
'MM/DD/YYYY HH:MI:SS.FF6 AM TZHTZM') from dual
)
select *
from your_table
where LOG_ENTRY_TIMESTAMP >= date '2018-02-15' - 1/24
and LOG_ENTRY_TIMESTAMP < date '2018-02-16' + 23/24;
I LOG_ENTRY_TIMESTAMP
- ---------------------------------
B 2018-02-14 23:02:19.224528 -05:00
C 2018-02-16 01:02:19.412528 -05:00
但是,您需要验证用于变量的值的实际数据类型是什么,以及是否正在执行任何时区转换,这可能会影响实际匹配的值范围。