简体   繁体   English

在一列中合并两列

[英]Combine two columns in one column

I have column 1 and column 2, and want to combine them into column 3 of the same table. 我有第1列和第2列,并希望将它们组合到同一个表的第3列。 If the column 2 is null then display column 1 value, if column 1 is null, them display column 2 data. 如果列2为null,则显示列1值,如果列1为空,则显示列2数据。 If both of them are null, then display null. 如果它们都为null,则显示null。 I tried two things: 我尝试了两件事:

1) using CONCAT SELECT CONCAT(Column1, Column2) AS Column3 FROM TEST_ATTRIBUTES . 1)使用CONCAT SELECT CONCAT(Column1, Column2) AS Column3 FROM TEST_ATTRIBUTES

It just merges the columns only when both of them are not null. 它只是在两个列都不为空时才合并列。 otherwise it just prins null. 否则它只是prins null。

2) using (column1 + column 2). 2)使用(column1 + column 2)。

SELECT (Column1 + Column2) AS Column3 FROM TEST_ATTRIBUTES . SELECT (Column1 + Column2) AS Column3 FROM TEST_ATTRIBUTES

doesn't show desired output. 没有显示所需的输出。

I'm writing this code in java. 我在java中编写这段代码。 Thanks 谢谢

use COALESCE() , this doesn't concatenate but returns the first non-null value from the list. 使用COALESCE() ,这不会连接,但会从列表中返回第一个非空值。

SELECT Column1, 
       Column2, 
       COALESCE(Column1, Column2) AS Column3 
FROM   TEST_ATTRIBUTES

if there are chances that both of them are null, 如果它们都有可能是空的,

SELECT Column1, 
       Column2, 
       IF(Column1 IS NULL AND Column2 IS NULL, NULL, CONCAT(COALESCE(Column1,''), COALESCE(Column2,''))) AS Column3 
FROM   TEST_ATTRIBUTES

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

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