【问题标题】:Update column based between two times Daily基于两次每日更新列
【发布时间】:2019-12-01 12:14:15
【问题描述】:

我想要一个 SQL 代码来根据每天的时间间隔更新列 area

我的 start_time 列也是 varchar2,而不是 date

例如:

between 06:00:00 and 10:00:00 = 'A'<br>
between 10:00:00 and 15:30:00 = 'B'<br>
between 15:30:00 and 22:00:00 = 'C'<br>

表名:myTable

   id    name        start_time        area
    ============================================
    1     a        06/07/19 11:00        -
    2     b        06/07/19 09:00        -
    3     c        06/07/19 11:00        -
    4     d        07/07/19 13:00        -
    5     e        07/07/19 21:00        - 
    6     f        08/07/19 16:00        -
    7     g        08/07/19 01:00        -
    8     h        08/07/19 18:00        -

结果:

   id    name       start_Time         area
  ============================================
    1     a        06/07/19 11:00        B
    2     b        06/07/19 09:00        A
    3     c        06/07/19 11:00        B
    4     d        07/07/19 13:00        B
    5     e        07/07/19 21:00        C 
    6     f        08/07/19 16:00        C
    7     g        08/07/19 01:00        -
    8     h        08/07/19 18:00        C

我做了一个有效的 SQL 查询:

select * 
from myTable 
where  TO_CHAR(TO_DATE(TIME_START,'YYYY-MM-DD HH24:MI:SS'), 'HH24:MI:SS') 
       BETWEEN TO_CHAR(TO_DATE('2019/11/11/ 06:00:00','YYYY-MM-DD HH24:MI:SS'), 'HH24:MI:SS') 
       AND TO_CHAR(TO_DATE('2019/11/11/ 13:30:00','YYYY-MM-DD HH24:MI:SS'), 'HH24:MI:SS')

但我创建了一个列,现在我想在记录而不是查询上更新它。

【问题讨论】:

  • 您只需要一个CASE 声明来更新您的记录。见这里stackoverflow.com/questions/18760632/…
  • 与您的问题无关,但是:绝不,请在已经是日期的值上调用to_date()。这将首先将date 值转换为varchar,然后将varchar 转换回最初的date
  • 由于某种原因我的列 time_start 是 varchar2 而不是日期列
  • 这是一个非常糟糕的主意

标签: sql oracle datetime sql-update


【解决方案1】:

您可以使用to_char()case 表达式:

update mytable
    set area = (case when to_char(start_time, 'HH24:MI') >= '06:00' and to_char(start_time, 'HH24:MI') < '10:00'
                     then 'A'
                     when to_char(start_time, 'HH24:MI') >= '10:00' and to_char(start_time, 'HH24:MI') < '15:30'
                     then 'B'
                     when to_char(start_time, 'HH24:MI') >= '15:30' and to_char(start_time, 'HH24:MI') < '22:00'
                     then 'C'
                end);

【讨论】:

    【解决方案2】:

    我的错误是我的 time_start 列是 varchar2,而不是 date 列, 所以有了这段代码就可以了

    update myTable 
        set area = (case when substr(time_start,10,8) >= '06:00:00' and substr(time_start,10,8) <= '06:59:59' then 'A' 
                         when substr(time_start,10,8) >= '07:00:00' and substr(time_start,10,8) <= '07:59:59' then 'B' 
                         when substr(time_start,10,8) >= '08:00:00' and substr(time_start,10,8) <= '08:59:59' then 'C' 
    end);
    

    -

    谢谢

    【讨论】:

      猜你喜欢
      • 2020-11-25
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多