Oracle SQL:如何修改查询以仅在特定时间范围内获得结果?

Oracle SQL: How to modify query in order to get only results within a certain timeframe?

我在 Oracle SQL 开发人员中使用此语句

select to_char(time,'DD/MM/YY hh24'),count(column) as xyz from table
where to_char(time,'DD/MM/YY')>= '08/04/21'
and to_char(time,'DD/MM/YY')<= '09/04/21'
and column='xyz'
group by to_char(time,'DD/MM/YY hh24')
order by to_char(time,'DD/MM/YY hh24');

我期望的是 result/table,其中结果按时间升序排列(从 08/04/21 的最早小时开始,到 09/04/21 的最晚结束。我希望只有 08/04/2109/04/21 天的条目。相反,我得到的结果还包括其他日期,例如 09/02/2108/12/20

如何修改我的查询?

假设 time 的数据类型为 date,您不想在 where 子句或 [=] 中对其执行 to_char 15=]。如所写,您正在进行字符串比较而不是日期比较,因此您得到的是 to_char(time 字符串在两个值之间按字母顺序排序的行,而不是日期在两个日期之间的行。与日期文字进行比较或对字符串文字进行显式 to_date 调用

我打赌你真的想要这样的东西

select trunc(time, 'HH24'),count(column) as xyz 
  from table
 where time >= date '2021-08-04'
   and time <= date '2021-09-04'
   and column='xyz'
 group by trunc(time, 'HH24')
 order by trunc(time, 'HH24');

您正在将本机日期值转换为字符串(使用两位数年份!),然后比较这些字符串。字符串“08/12/20”是 'less than' 字符串“09/04/21”。

将您的日期与其他日期进行比较,这更容易作为文字:

select to_char(trunc(time, 'HH'), 'DD/MM/YY HH24'), count(column) as xyz
from table
where time >= date '2021-04-08'
and time < date '2021-04-10'
and column='xyz'
group by trunc(time, 'HH')
order by trunc(time, 'HH');

我使用了 trunc() 到 remove/zero 分和秒部分,这意味着您可以按该值进行分组和排序;最后转换成字符串显示即可。

我还将 to_char(time,'DD/MM/YY')<= '09/04/21' 转换为 time < date '2021-04-10' 而不是 time < date '2021-04-09',因为您的版本包含了 9 日的所有数据;这可能是也可能不是你想要的 - 你可能一直在努力争取一天。

db<>fiddle demo