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