简体   繁体   English

在Oracle SQL中按时间查询数据

[英]Querying data by time in Oracle SQL

I have a table in Oracle in which data is inserted from different sources. 我在Oracle中有一张表,其中的数据是从不同来源插入的。 In 2014, we discovered that some sources were not inserting the time stamp with the date, we however fixed them and now all sources insert data in proper format, example 05/04/2015 4:30:42 PM 2014年,我们发现某些来源未在日期中插入时间戳,但是我们对其进行了修复,现在所有来源05/04/2015 4:30:42 PM正确的格式插入数据,例如05/04/2015 4:30:42 PM

Using a SQL query, we want to divide the data into 3 types, morning shift, evening shift and no shift (for data without the time stamp). 通过使用SQL查询,我们希望将数据分为3种类型,晨班,晚班和无班(对于没有时间戳的数据)。

Morning shift will be between 00:00:00 and 14:30:00 早班时间为00:00:0014:30:00

Evening shift will be between 14:31:00 and 23:59:00 晚上14:31:00时间为14:31:0023:59:00

I have written the query in 2 different ways as follows: 我用以下两种不同的方式编写了查询:

(a) (一种)

 CASE
        WHEN TO_DATE(DATEANDTIME,'MM/DD/YYYY HH24:MI:SS') BETWEEN (TO_DATE ('00:00:00', 'HH24:MI:SS')) AND (TO_DATE ('14:30:00', 'HH24:MI:SS'))
        THEN
           'MORNING SHIFT'
        WHEN TO_DATE(DATEANDTIME,'MM/DD/YYYY HH24:MI:SS') BETWEEN (TO_DATE ('14:31:00', 'HH24:MI:SS')) AND  (TO_DATE ('23:59:00', 'HH24:MI:SS'))
        THEN
           'EVENING SHIFT'
        ELSE
          'NO SHIFT'
     END SHIFT

(b) (b)中

CASE
        WHEN DATEANDTIME BETWEEN (TO_DATE ('00:00:00', 'HH24:MI:SS')) AND (TO_DATE ('14:30:00', 'HH24:MI:SS'))
        THEN
           'MORNING SHIFT'
        WHEN DATEANDTIME BETWEEN (TO_DATE ('14:31:00', 'HH24:MI:SS')) AND  (TO_DATE ('23:59:00', 'HH24:MI:SS'))
        THEN
           'EVENING SHIFT'
        ELSE
          'NO SHIFT'
     END SHIFT

Query (a) returns an error ORA-01858: a non-numeric character was found where a numeric was expected but Query (b) displays data with everything going to NO SHIFT 查询(一)返回一个错误ORA-01858: a non-numeric character was found where a numeric was expected ,但查询(b)展示的一切数据将NO SHIFT

Sample data of the table is as follows of the dateandtime field: 该表的样本数据如下日期和dateandtime字段:

05/04/2015 10:43
05/04/2015 16:52
05/04/2015 19:27
11/04/2009

Kindly guide me to the correct query and what am I doing wrong, the same conditions works in TOAD fine. 请指导我正确的查询和我在做什么错,相同的条件在TOAD正常工作。

You can convert the value to a string and do the comparison as strings: 您可以将值转换为字符串,然后以字符串形式进行比较:

(case when to_char(dateandtime, 'HH24:MI') BETWEEN '00:00' and '14:30'
      then 'MORNING SHIFT'
      when to_char(dateandtime, 'HH24:MI') BETWEEN '14:31' and '23:59'
      then 'EVENING SHIFT'
      else 'NO SHIFT'
 end) as SHIFT

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM