关于sql中的日期
这是我的查询:
select *
from test n
WHERE lower(process_name) like 'test%'
AND ( test_id is NULL
OR TO_CHAR(ADD_MONTHS(TRUNC(SYSDATE),-6),'YYYYMM') > TO_CHAR(n.process_date,'YYYYMM')
我想检查查询中的日期字段 process_date
是否大于 6 个月。
Here's my query:
select *
from test n
WHERE lower(process_name) like 'test%'
AND ( test_id is NULL
OR TO_CHAR(ADD_MONTHS(TRUNC(SYSDATE),-6),'YYYYMM') > TO_CHAR(n.process_date,'YYYYMM')
I want check whether date field process_date
is greater than 6 months in the query.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我没有方便的 Oracle 实例来测试 Oracle 是否会对 TO_CHAR 结果进行隐式数据类型转换,因为它将完全是数字。尽管如此,与 TRUNC'd DATE 值相比,对我来说似乎过于复杂...
对于 Oracle 中六个月或更早的记录:
如果您想要更早但不完全包括六个月 - 删除等于运算符:
对于MySQL 中六个月或更长的时间:
如果您想要更早的时间但不完全包括六个月 - 删除等于运算符:
对于 MySQL,DATE 的性能与 Oracle 的 TRUNC 类似。
I don't have an Oracle instance handy to test if Oracle will do implicit data type conversion on the TO_CHAR results being that it will be entirely numeric. Still, seems over complicated to me when comparing to a TRUNC'd DATE value...
For records that are six months or older in Oracle:
If you want older but not including six months exactly - remove the equals operator:
For records that are six months or older in MySQL:
If you want older but not including six months exactly - remove the equals operator:
For MySQL, DATE is performing similar to Oracle's TRUNC.
MONTHS_BETWEEN( date1, date2) 返回 (date1 - date2),因此参数的顺序很重要
如果您希望月份数字相差 6,例如,如果这对您来说是错误的
那么您应该:
保证正确比较月份的最后几天并返回整数
注意:这两个查询都不会使用“process_date”上的索引(如果可用)。对于“索引”解决方案,请参阅OMG Ponies 的帖子以及对此的评论
MONTHS_BETWEEN( date1, date2) returns (date1 - date2), so order of args is significant
If you want the months' numbers to differ by 6, for example if this is wrong for you
Then you should:
Last days of months are guaranteed to compare correctly and return whole number
NOTE: both those queries will not use index on "process_date", if its available. For 'indexed' solution see post by OMG Ponies and comments to this one
如果您使用的是 SQL Server,则可以使用 DATEDIFF()。请参见下面的示例。
你可以由此推导出一个答案。如果我没有达到目标,请告诉我。
谢谢。
If you're using SQL Server, you can use DATEDIFF(). See below example.
You can deduct an answer from this. Please let me know if I've missed the target.
Thanks.