Home  >  Q&A  >  body text

How to use Update in Case statement with columns as aliases

<p>I have a table called sales_data with 3 columns (id int, udf varchar(20), date_of_sale datetime). I am trying to find the weekday of date_of_sale column by adjusting the time to 6 hours, now I have to update the udf column to the weekday corresponding to date_of_sale. I have an idea for a select query, but how do I update the udf column? </p> <pre class="brush:php;toolbar:false;">select weekday(subtime(s.date_of_sale ,'6:0:0')) as putdata, CASE WHEN weekday(subtime(s.date_of_sale ,'6:0:0'))=0 THEN 'Sunday' WHEN weekday(subtime(s.date_of_sale ,'6:0:0'))=1 THEN 'Monday' WHEN weekday(subtime(s.date_of_sale ,'6:0:0'))=2 THEN 'Tuesday' WHEN weekday(subtime(s.date_of_sale ,'6:0:0'))=3 THEN 'Wednesday' WHEN weekday(subtime(s.date_of_sale ,'6:0:0'))=4 THEN 'Thursday' WHEN weekday(subtime(s.date_of_sale ,'6:0:0'))=5 THEN 'Friday' WHEN weekday(subtime(s.date_of_sale ,'6:0:0'))=6 THEN 'Saturday' END as udf from sales_data s;</pre></p>
P粉214089349P粉214089349411 days ago504

reply all(2)I'll reply

  • P粉256487077

    P粉2564870772023-09-06 14:26:54

    Add generated columns (https://dev.mysql.com/doc/refman/8.0/en/create-table-generated-columns.html) to simplify processing , and avoid data inconsistencies:

    alter table sales_data add weekday varchar(10) GENERATED ALWAYS
      AS (CASE   
        WHEN weekday(subtime(s.date_of_sale ,'6:0:0'))=0 THEN 'Sunday'  
        WHEN weekday(subtime(s.date_of_sale ,'6:0:0'))=1 THEN 'Monday'  
        WHEN weekday(subtime(s.date_of_sale ,'6:0:0'))=2 THEN 'Tuesday'  
        WHEN weekday(subtime(s.date_of_sale ,'6:0:0'))=3 THEN 'Wednesday'  
        WHEN weekday(subtime(s.date_of_sale ,'6:0:0'))=4 THEN 'Thursday'  
        WHEN weekday(subtime(s.date_of_sale ,'6:0:0'))=5 THEN 'Friday'  
        WHEN weekday(subtime(s.date_of_sale ,'6:0:0'))=6 THEN 'Saturday'  
    END );

    View the demo: https://dbfiddle.uk/2d5iIvBv

    (I don't get the same weekdays, maybe it's the locale?)

    reply
    0
  • P粉035600555

    P粉0356005552023-09-06 14:04:15

    Your above query is almost complete. You just need to add update statements.

    The query below should work for you.

    update sales_data 
    set udf = case   
        when weekday(subtime(date_of_sale,'6:0:0')) = 0 then 'Sunday'  
        when weekday(subtime(date_of_sale,'6:0:0')) = 1 then 'Monday'  
        when weekday(subtime(date_of_sale,'6:0:0')) = 2 then 'Tuesday'  
        when weekday(subtime(date_of_sale,'6:0:0')) = 3 then 'Wednesday'  
        when weekday(subtime(date_of_sale,'6:0:0')) = 4 then 'Thursday'  
        when weekday(subtime(date_of_sale,'6:0:0')) = 5 then 'Friday'  
        when weekday(subtime(date_of_sale,'6:0:0')) = 6 then 'Saturday'  
     end;

    reply
    0
  • Cancelreply