簡體   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