简体   繁体   English

SQL Server 2008 R2-合并结果

[英]SQL Server 2008 R2 - Combine results

I have a pretty simple table. 我有一张非常简单的桌子。 It has a key column and 4 further columns each denoting a different datatype. 它具有一个键列和另外4个列,每个列表示不同的数据类型。 The rules are this: 规则是这样的:

  1. Each row has a completed key value 每行都有一个完整的键值
  2. For each row the 4 remaining columns might be all empty 对于每一行,其余4列可能都为空
    or 要么
  3. For each row only 1 of the 4 remaining columns will be populated 对于每一行,仅填充剩余的4列中的1列

What I'm trying to achieve is to write a query which will result in two columns only (the key and the 1 of the 4). 我要实现的目标是编写一个查询,该查询将仅导致两列(键和4中的1)。 Essentially condensing the 4 columns ito one. 本质上将4列浓缩为1列。

The datatypes of the 4 columns is as follows: 4列的数据类型如下:

nvarchar(255)
numeric(32, 5)
datetime
nvarchar(MAX)

Source Data 源数据

╔═════╦═══════════╦══════╦════════════╦════════════════╗
║ key ║   col1    ║ col2 ║    col3    ║      col4      ║
╠═════╬═══════════╬══════╬════════════╬════════════════╣
║   1 ║ some text ║ null ║ null       ║ null           ║
║   2 ║ null      ║ 5    ║ null       ║ null           ║
║   3 ║ null      ║ null ║ null       ║ null           ║
║   4 ║ null      ║ null ║ 23/02/2017 ║ null           ║
║   5 ║ null      ║ null ║ null       ║ much more text ║
╚═════╩═══════════╩══════╩════════════╩════════════════╝

Ideal Output 理想输出

╔═════╦════════════════╗
║ key ║     newCol     ║
╠═════╬════════════════╣
║   1 ║ some text      ║
║   2 ║ 5              ║
║   3 ║ null           ║
║   4 ║ 23/02/2017     ║
║   5 ║ much more text ║
╚═════╩════════════════╝

Any help appreciated. 任何帮助表示赞赏。

The coalesce() function can work, but only if you convert all the values to strings: 仅当您将所有值都转换为字符串时, coalesce()函数才能工作:

select id,
       coalesce(col1,
                cast(col1 as nvarchar(255)),
                cast(col2 as nvarchar(255)),
                cast(col3 as nvarchar(255))
               ) as col

You could use COALESCE like this 您可以像这样使用COALESCE

select id, coalesce(cast(column1 as nvarchar(255)), cast(column2 as nvarchar(255)), cast(coulmn3 as nvarchar(255)), cast(column4 as nvarchar(255)) 
from ...

If they are all NULL then NULL will be returned. 如果它们全部为NULL则将返回NULL Otherwise, if we are guaranteed to have only one of the four columns NOT NULL then this one will be returned. 否则,如果保证我们只有四列NOT NULL之一,则将返回这一列。

You should use isnull . 您应该使用isull

select key, isnull(col1,col2,col3,col4) as newCol ......

Using COALESCE may create problem sometimes due to data type precedence . 有时由于数据类型优先级的原因,使用COALESCE可能会产生问题。 Since COALESCE determines the type of the output based on data type precedence. 由于COALESCE根据数据类型优先级确定输出的类型。

Check the below link for more details. 检查以下链接以获取更多详细信息。

Reference 参考

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

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