简体   繁体   中英

How to add a new column based on the value in the field `time`

I have table:

+--------+--------------+-----------+   
| person |.....DAY......| ....hours |  
| Name1 ....2014-01-08... 03:53:23  |   
| Name2 ....2014-01-08... 05:30:54  |  
+--------|--------------|-----------+

How can I add a new column label based on the value in the field of time? If time from 05:00:00 to 11:00:00 the value will be '1' , else '0' . It should look something like this:

+---------+--------------+-----------+---------+  
| person  |.....DAY......| ..hours  |  label   |   
| Name1 ....2014-01-08... 03:53:23  |  0 ......|   
| Name2 ....2014-01-08... 05:30:54  |  1.......|   
+---------+--------------+----------+----------+

你可以用这样的东西

update table set label = case when hour(hours) between 5 and 10 then 0 else 1 end;

Since this is a calculated column you can generate it on-the-fly in your queries like this

SELECT person, 
       DATE( dt ) AS DAY , 
       case when hour(from_unixtime(sec_to_time(SUM( IF( source LIKE '%вход' OR source LIKE '%въезд', -1, 1 ) * UNIX_TIMESTAMP( dt ) )))) between 5 and 11 
            then 1
            else 0 
       end AS hours
from your_table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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