[英]Join columns if one of them is null
I have 3 columns: 我有3栏:
col1, int
col2, char(10)
col3, char(11)
only one of them has any value in them, and it can be either one of them. 其中只有一个具有任何价值,也可以是其中之一。
i want to check which columns are null and add the one, whcih has a value to a fourth column: col4. 我想检查哪些列为空并添加一列,其中有一个值到第四列:col4。
i use T-SQL 我使用T-SQL
Try this 尝试这个
select col1,col2,col3, coalesce(col1, coalesce(col2,col3)) as col4
from your_table
COALESCE returns the first non-null expr in the expression list.
COALESCE返回表达式列表中的第一个非空expr。 If all occurrences of expr evaluate to null, then the function returns null.
如果所有出现的expr评估为null,则该函数返回null。
You could use IS NULL
comparison to return a boolean true or false for each column and COALESCE()
to find the first non-null value among all the columns 您可以使用
IS NULL
比较为每个列返回布尔值true或false,并使用COALESCE()
查找所有列中的第一个非null值
SELECT
col1 IS NULL AS col1_null,
col2 IS NULL AS col2_null,
col3 IS NULL AS col3_null,
COALESCE(cast(col1 as char(11)), cast(col2 as char(11)), cast(col3 as char(11)) AS first_not_null_val
FROM table
Order of columns provided within COALESCE()
function matters, but since you have only one of those three that is not null, then it would always return that one. COALESCE()
函数中提供的列顺序很重要,但是由于您只有这三个不为null的列之一,因此它将始终返回该列。
Note : You need to cast your columns to the same datatype for COALESCE()
. 注意 :您需要将列强制转换为
COALESCE()
的相同数据类型。 Since your upper bound is char(11)
because it covers both char(10)
and int
type I've come up with that. 由于您的上限是
char(11)
因为它同时涵盖了char(10)
和int
类型,因此我想出了这一点。 I imagine that you want to keep the spaces which is why you use char
in the first place. 我想您想保留空格,这就是为什么首先使用
char
原因。
SELECT COALESCE(CONVERT(CHAR(11), col1), CONVERT(CHAR(11), col2), col3)
FROM yourtable;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.