如何从oracle数据库中选择2个日期不在同一月份和年度的记录。
下表是示例,在这里,我希望所有创建日期和更新日期的记录不在同一月和年中。
毫秒(ex.1454738400000)和两个日期字段的数据类型是数字(32)。
---------------------------------
id| Created Date | Updated Date |
---------------------------------
1 | 02/26/2018 | 02/26/2017 |
---------------------------------
2 | 03/28/2018 | 03/26/2018 |
---------------------------------
3 | 04/26/2018 | 04/28/2017 |
---------------------------------
4 | 02/26/2018 | 02/26/2016 |
---------------------------------
请看以下两个选项:
select record_id
from your_table
where to_char(created_date, 'mm.yyyy') <> to_char(updated_date, 'mm.yyyy');
select record_id
from your_table
where trunc(created_date, 'yyyy') <> trunc(updated_date, 'yyyy')
and trunc(created_date, 'mm') <> trunc(updated_date, 'mm');
如果涉及大量数据,请考虑在日期列中创建基于功能的索引。
[edit]
如果这些值确实是数字,则必须先将它们转换为日期数据类型,然后应用TRUNC
函数。例如:
SQL> select trunc(to_date(20190226, 'yyyymmdd'), 'yyyy') result from dual;
RESULT
----------
01.01.2019
SQL>
请注意,如果格式错了,例如20190231(应该是2019年2月31日),因为2月没有31天。
如果可能的话,将这些列的数据类型更改为日期。