日期:2014-05-17  浏览次数:21036 次

日期时间段的sql,怎么写?
数据库表A,字段commit_time存的数据是:20080301112536等。现在我要查询出今天在9:00到10:00,15:00至16:00时间段的数据。请问如何写这样的语句。谢谢!!!

------解决方案--------------------
select * from youtablename where commit_time>=to_char(sysdate,'yyyymmdd')||'0900' and commit_time<=to_char(sysdate,'yyyymmdd')||'1000'


select * from youtablename where commit_time>=to_char(sysdate,'yyyymmdd')||'1500' and commit_time<=to_char(sysdate,'yyyymmdd')||'1600'
------解决方案--------------------
SQL code

select * 
from youtablename  
where commit_time between to_char(sysdate,'yyyymmdd')||'0900' and to_char(sysdate,'yyyymmdd')||'1000' 
UNION ALL
select * 
from youtablename  
where commit_time between to_char(sysdate,'yyyymmdd')||'1500' and to_char(sysdate,'yyyymmdd')||'1600'

------解决方案--------------------
select * from A where substr(commit_time, 9) between '090000' and '100000' or substr(commit_time, 9) between '150000' and '160000' 
如果不含后面的时间点则应该为:
select * from A where substr(commit_time, 9) between '090000' and '095959' or substr(commit_time, 9) between '150000' and '155959'
------解决方案--------------------
commit_time 字段如果是字符类型 可以先将转换成日期类型to_date 然后再 to_char转换成字符

select to_char(to_date( '20080301112536 ', 'yyyymmddhhmiss '), 'Hh24:mi:ss ') from dual

下面的代码 可以试试。。。。自己把表名和列名改下。
select
a.commit_id,
a.commit_name,
a.commit_time
from
(select commit_id,
commit_name,
commit_time,
case when to_char(to_date( '20080301112536 ', 'yyyymmddhhmiss '), 'Hh24:mi ')> = '09:00 '
and to_char(to_date( '20080301112536 ', 'yyyymmddhhmiss '), 'Hh24:mi ') <= '10:00 ' then 1
when to_char(to_date( '20080301112536 ', 'yyyymmddhhmiss '), 'Hh24:mi ')> = '09:00 '
and to_char(to_date( '20080301112536 ', 'yyyymmddhhmiss '), 'Hh24:mi ') <= '10:00 ' then 1
else 0
end temp_column
from table_name ) a
where a.temp_column = 1