sql - 使用 Oracle SQL 选择生日在给定范围内的员工

标签 sql database oracle datetime date-arithmetic

为了选择两个月之间的生日,其中 FROMDATE 和 TODATE 是准备好的语句中的一些参数,我想是这样的:

select
  p.id as person_id,
   ...
   ...
  where e.active = 1
        and extract(month from TODATE) >= extract(month from e.dateOfBirth)
        and extract(month from e.dateOfBirth) >= extract(month from FROMDATE)
        order by extract(month from e.dateOfBirth) DESC,
              extract(day from e.dateOfBirth) DESC

如何改进以适应天数?

最佳答案

在 Oracle 中搜索日期范围的方法不止一种。对于您的场景,我建议您将涉及的所有日期的月份和日期元素转换为数字。

select
  p.id as person_id,
   ...
   ...
  where e.active = 1
  and to_number (to_char( e.dateOfBirth, 'MMDD')) 
      between to_number (to_char( FROMDATE, 'MMDD'))
              and to_number (to_char( TODATE, 'MMDD')) 
  order by extract(month from e.dateOfBirth) DESC,
          extract(day from e.dateOfBirth) DESC

这不会在 e.dateOfBirth 列上使用任何索引。这是否重要取决于您希望多久运行一次查询。


@AdeelAnsari 评论:

" I don't like to to_char the predicate, in order to make use of index"

什么指标? dateOfBirth 上的普通索引不会有任何用处,因为索引条目将以年份元素开头。因此,它不会帮助您找到在 任何 12 月 23 日出生的人的所有记录。

基于函数的索引——或者在 11g 中,带有索引的虚拟列(基本上是同一件事)——是对日期列的部分进行索引的唯一方法。

关于sql - 使用 Oracle SQL 选择生日在给定范围内的员工,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9861529/

相关文章:

mysql - 在 MySql 的滑动时间窗口内运行每个 id 的总数

sql - 性能 : Subquery or Joining

sql - 学习如何编写复杂的存储过程

mysql - 每100ms读一次mysql表可以吗?

mysql - 如何在sql中级联3个表

SQL Server错误: Primary file group is full

mysql - 标准化、高效的 SQL 数据库设计

mysql - 当计算机意外关闭时,mysql 数据会发生什么情况?

sql - 如何使用 TQuery 和 Oracle SQL 语法进行变量赋值和参数?

sql - 如何在 SQL 中仅提取字符串的第二个单词?