繁体   English   中英

SQL 服务器 - 根据其他列的值更新一列

[英]SQL server - Update one column based on the values of other columns

假设表中有五列,我想根据列 A、B、C、D 的值更新列 E。 如果对应的值为 Y,则将列名作为 E 列中值的一部分写入。预期结果显示在第二张图像中。

原来表中的数据是这样的

在此处输入图像描述

预期结果:

在此处输入图像描述

如果您的列数是固定的,那么您可以使用CASE语句。

样本数据

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');

解决方案

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;

结果

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 小提琴

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
                     );

但是,在可以计算时存储这些信息似乎很愚蠢 - 并且始终是最新的:

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
                                 )
                        );

计算列在查询时计算。 它们始终是最新的,无需更新。

update table_name set E='A,C,D' where A='Y' and B='N' and C='Y' and D='Y'

如果您为表设置 id 列,则很容易更新

暂无
暂无

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

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