[英]SQL server - Update one column based on the values of other columns
Say there are five columns in the table and I'd like to update the column E based on the value of column A,B,C,D.假设表中有五列,我想根据列 A、B、C、D 的值更新列 E。 If the corresponding value is Y, then write the column name as part of the value in column E. The expected result is shown in the second image.
如果对应的值为 Y,则将列名作为 E 列中值的一部分写入。预期结果显示在第二张图像中。
Originally, the data in the table looks like this原来表中的数据是这样的
Expected result:预期结果:
If you number of columns is fixed, then you can use a CASE
statement.如果您的列数是固定的,那么您可以使用
CASE
语句。
Sample data样本数据
create table data
(
A nvarchar(1),
B nvarchar(1),
C nvarchar(1),
D nvarchar(1),
E nvarchar(10)
);
insert into data (A, B, C, D) values
('Y', 'N', 'Y', 'Y'),
('N', 'N', 'N', 'Y'),
('N', 'Y', 'Y', 'N'),
('Y', 'Y', 'Y', 'N');
Solution解决方案
update d
set d.E = substring(
case d.A when 'Y' then ',A' else '' end
+ case d.B when 'Y' then ',B' else '' end
+ case d.C when 'Y' then ',C' else '' end
+ case d.D when 'Y' then ',D' else '' end,
2, 100)
from data d;
Result结果
select * from data;
A B C D E
--- --- --- --- -------
Y N Y Y A,C,D
N N N Y D
N Y Y N B,C
Y Y Y N A,B,C
SQL Server now supports CONCAT_WS()
, which I would recommend: SQL 服务器现在支持
CONCAT_WS()
,我建议:
update t
set E = concat_ws(',',
case d.A when 'Y' then 'A' end,
case d.B when 'Y' then 'B' end,
case d.C when 'Y' then 'C' end,
case d.D when 'Y' then 'D' end
);
However, it seems silly to store this information when it can be calculated -- and always up-to-date:但是,在可以计算时存储这些信息似乎很愚蠢 - 并且始终是最新的:
alter table t add E as (concat_ws(',',
case d.A when 'Y' then 'A' end,
case d.B when 'Y' then 'B' end,
case d.C when 'Y' then 'C' end,
case d.D when 'Y' then 'D' end
)
);
Computed columns are calculated when they are queried.计算列在查询时计算。 They are always up-to-date and never have to be updated.
它们始终是最新的,无需更新。
update table_name set E='A,C,D' where A='Y' and B='N' and C='Y' and D='Y'
If you set id column for your table it is easy to update如果您为表设置 id 列,则很容易更新
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.