简体   繁体   English

使用SQL中多个列中的值创建列

[英]Create column with values from multiple columns in SQL

I want to add a column to a table that includes value from one of two columns, depending on which row contains the value. 我想向表添加一列,该表包含两列之一的值,具体取决于哪一行包含该值。

For instance, 例如,

SELECT
  concat("Selecting Col1 or 2", cast("Col1" OR "Col2" as string)) AS relevantinfo,
FROM table

I do not know much SQL and I know this query does not work. 我不太了解SQL,而且我知道此查询无法正常工作。 Is this even possible to do? 这有可能吗?

Col1    Col2
1       
         4
3
4
         5

FINAL RESULT 最后结果

Col1    Col2    relevantinfo
1                1
        4        4
3                3
4                4
        5        5

You can use the COALESCE function, which will return the first non-null value in the list. 您可以使用COALESCE函数,该函数将返回列表中的第一个非空值。

SELECT col1, col2, COALESCE(col1, col2) AS col3 
FROM t1;

Working example: http://sqlfiddle.com/#!9/05a83/1 工作示例: http : //sqlfiddle.com/#!9/05a83/1

I wouldn't alter the table structure to add a redundant information that can be retrieved with a simple query. 我不会更改表结构以添加可以通过简单查询检索的冗余信息。

I would rather use that kind of query with IFNULL/ISNULL(ColumnName, 'Value to use if the col is null') : 我宁愿将这种查询与IFNULL/ISNULL(ColumnName, 'Value to use if the col is null')

--This will work only if there can't be a value in both column at the same time
--Mysql
SELECT CONCAT(IFNULL(Col1,''),IFNULL(Col2,'')) as relevantinfo FROM Table

--Sql Server
SELECT CONCAT(ISNULL(Col1,''),ISNULL(Col2,'')) as relevantinfo FROM Table

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

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