如何根据 SQL 中的条件替换列中的值?

huangapple go评论79阅读模式
英文:

How to replace values in a column based on a condition in SQL?

问题

抱歉,如果这个问题有点儿愚蠢,因为我对SQL还相对陌生。

我有一个表格(TEST),包含3列,这三列都是ID列。

我想要在列A中替换值为列B中的值,前提是列B中的值不是NULL

如果列B中的值是NULL,我想要用列C中的值来替换列A中的值。

谢谢!

英文:

Apologies if this is a silly questions as I am fairly new to SQL.

I have a table (TEST) with 3 columns; all three columns are ID columns.

I want to replace the values in column A with the values in column B if the values in column B are not NULL.

If values in column B are NULL I want to replace the values in column A with the values of column C.

Thanks!

答案1

得分: 2

对于常见的“当列为空时使用其他值”的需求,SQL数据库管理系统提供了几种选项 - 通常是函数,例如 IFNULL()NVL()COALESCE()

在这种情况下,COALESCE 是一个很好的选择,因为它简洁明了,并且直接满足需求:它返回从左到右的第一个输入参数的值,该参数不为 NULL

结合 UPDATE 命令,可以使用以下方式创建所需的效果:

UPDATE test
   SET a = COALESCE(b, c);

提示: 为了预览 UPDATE 语句的结果,可以随时编写相应的 SELECT 语句:

SELECT a
     , b
     , c
     , COALESCE(b, c) AS new_a
FROM 
    test;
英文:

For the common "when column IS NULL then use some other value" requirement SQL DBMS provide several options - typically functions e.g. IFNULL(), NVL(), COALESCE().

COALESCE is a good choice in this case as it is concise and maps to the requirement in a direct way: it returns the value of the first input parameter - starting from the left-most - that is not NULL.

Combined with the UPDATE command the desired effect can be created with:

UPDATE test
   SET a = COALESCE(b, c);

Hint: in order to pre-view what the result of the UPDATE statement will look like, one can always write a corresponding SELECT statement:

SELECT a
     , b
     , c
     , COALESCE(b, c) AS new_a
FROM 
    test;

答案2

得分: 0

尝试这个:

CREATE TABLE #temp (
    Col_A nvarchar(10),
    Col_B nvarchar(10),
    Col_C nvarchar(10)
)

INSERT INTO #temp VALUES ('a', 'b', 'c')
INSERT INTO #temp VALUES ('aa', null, 'cc')
INSERT INTO #temp VALUES ('aaa', null, 'ccc')
INSERT INTO #temp VALUES ('aaaa', 'b', 'ccccc')

UPDATE #temp SET Col_A = CASE WHEN Col_B IS NOT NULL THEN Col_B ELSE Col_C END;
SELECT * FROM #temp;
DROP TABLE #temp;

请注意,我仅提供了代码的翻译部分。

英文:

Try this:

Create TABLE #temp (
Col_A nvarchar(10),
Col_B nvarchar(10),
Col_C Nvarchar(10)
)

insert into #temp values ('a', 'b', 'c')
insert into #temp values ('aa', null, 'cc')
insert into #temp values ('aaa', null, 'ccc')
insert into #temp values ('aaaa', 'b', 'ccccc')

UPDATE #temp  SET Col_A = CASE WHEN Col_B is Not Null THEN Col_B ELSE Col_C END;
SELECT * from #temp
Drop TABLE #temp

huangapple
  • 本文由 发表于 2023年6月16日 08:10:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76486216.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定