[英]Oracle query concatenate date
I have the following query:我有以下查询:
select *
from mytable
where to_char(mydate,'mm/dd/yyyy') between ('05/23/2013')
and ('06/22/2013')
I need to change it to make dynamically so that I won't modify it every month from 05/23/2013
to 06/23/2013
for example:我需要更改它以动态生成,这样我就不会从
05/23/2013
年 5 06/23/2013
05/23/2013
到06/23/2013
05/23/2013
06/23/2013
每个月都修改它,例如:
('05/23/' + (select to_char(sysdate, 'yyyy') from dual))
but this is giving an error.但这是一个错误。 Any suggestions?
有什么建议么?
What I need to do: Every month I need to run this query to get the records between 23 rd of this month and 23 rd of the last month.我需要做什么:我每个月需要运行该查询本月23日和23日的最后一个月之间获得的记录。
Oracle uses ||
Oracle 使用
||
as the concatenation operator :作为连接运算符:
('05/23/' || (select to_char(sysdate, 'yyyy') from dual))
BTW, David is right.顺便说一句,大卫是对的。 If you really want to compare string representations of dates (but why?), use a date format that is ordered the same way as dates:
如果您真的想比较日期的字符串表示(但为什么?),请使用与日期相同的日期格式:
to_char(mydate,'yyyy/mm/dd')
You're performing a comparison on strings, not on dates, so your code doesn't work the way you think it does.您正在对字符串而不是日期进行比较,因此您的代码无法按照您认为的方式工作。
Based on the string logic, "05/23/2000" is between "05/22/2013" and "06/24/2000".根据字符串逻辑,“05/23/2000”介于“05/22/2013”和“06/24/2000”之间。
Keep the data types as date and Oracle will get the comparison right.将数据类型保留为日期,Oracle 将正确进行比较。
Possibly what you want is:可能你想要的是:
select *
from my_table
where mydate >= add_months(trunc(sysdate,'MM'),-1)+22 and
mydate < trunc(sysdate,'MM')+22
but it's difficult to tell without a description of what the requirement actually is.但是如果不描述需求的实际情况,就很难说清楚。
How about this one?这个怎么样?
SELECT '(''05/23/'''||to_char(sysdate, 'yyyy')||'''' FROM DUAL
Have not testet because I have no Oracle database right now, needs checking for quote escapes...还没有测试,因为我现在没有 Oracle 数据库,需要检查报价转义...
Do you need exact days from the month?你需要一个月的确切天数吗? You can also substract days from sysdate:
您还可以从 sysdate 中减去天数:
SELECT (sysdate - 30) FROM DUAL
您也可以使用 concat 函数
concat('05/23/', (select to_char(sysdate, 'yyyy') from dual))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.