简体   繁体   中英

sql how to add value by condition and put in specific column

This is the table and data in the table.

Table:

id |value_total|value_1|value_2|value_3|value_4 
1  | 100       | 50    | 0     | 0     | 50
2  | 200       | 0     | 150   | 50    | 0
3  | 300       | 100   | 200   | 0     | 0
4  | 400       | 100   | 200   | 0     | 100

I need table having the below data.

desire result:

id |value_total|value_1|value_2|value_3|value_4 
1  | 100       | 0     | 0     | 0     | 100
2  | 200       | 0     | 0     | 200   | 0
3  | 300       | 0     | 300   | 0     | 0
4  | 400       | 0     | 0     | 0     | 400

Do you want to put the total value in the last non-zero column?

select id, value_total,
       (case when value_2 = 0 and value_3 = 0 and value_4 = 0 and value_1 > 0
             then value_total else 0
        end) as value_1,
       (case when value_3 = 0 and value_4 = 0 and value_2 > 0
             then value_total else 0
        end) as value_2,
       (case when value_4 = 0 and value_3 > 0
             then value_total else 0
        end) as value_3,
       (case when value_4 > 0 then value_total else 0 end)
from t;

There are many ways for this scenario ,one of them is mentioned below please have a look.

UPDATE TABLE
SET value_1 = 0
    ,value_2 = CASE 
        WHEN id = 3
            THEN 300
        ELSE 0
        END
    ,value_3 = CASE 
        WHEN id = 2
            THEN 200
        ELSE 0
        END
    ,value_4 = CASE 
        WHEN id = 1
            THEN 100
        WHEN id = 4
            THEN 400
        ELSE 0
        END

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