如何运行SQL查询从三列中的一列中提取数据?

时间:2016-07-07 20:08:42

标签: sql sql-server

我有一个数据库表" table_name1"在SQL Server 2012中,我使用的是SQL Server Management Studio版本10.

表格中的数据如下:

colpkey col1    col2    col3
1234    AB1234  AB1234  
1265    BS5379  BS5379  BS5379
2323    WE7865  WE7865  WE7865
3267            WB7690  WB7690
6543    NULL    DH6583  
8798                    NULL
9403    BF6543          NULL
9856    BH7548  BH7548  BH7548

我用来创建此表样本表的查询:

create table table_name1 (
  colpkey bigint primary key,
  col1 varchar(10) ,
  col2 varchar(10),
  col3 varchar(10)
);

我想编写一个查询,因此它应该拉两列," colpkey"和" col"。 " col"应该具有来自" col1"的价值。如果" col1"为NULL或空白然后它应该从" col2"获得值。如果" col2"是NULL或空白然后它应该从" col3"获得值。如果所有" col1"," col2"和" col3"是空白或NULL然后将值放入" col"应为空白('')。

因此对于给定的样本" table_name1"查询应该提取如下数据:

colpkey col
1234    AB1234
1265    BS5379
2323    WE7865
3267    WB7690
6543    DH6583
8798    
9403    BF6543
9856    BH7548

如何编写查询来执行此操作?我试图使用CASE并提出以下查询:

select colpkey, 
Case WHEN (col1 != null and col1!= '') then col1
     ELSE 
     (CASE WHEN (col2 != null and col2!= '') then col2
     ELSE
     (CASE WHEN (col3 != null and col3!= '') then col3
     ELSE '' END) END) END as col
from table_name1;

但每行显示空白,如:

colpkey col
1234    
1265    
2323    
3267    
6543    
8798    
9403    
9856    

请告知我查询错误的位置?

2 个答案:

答案 0 :(得分:5)

在SQL中,您无法将NULL!=进行比较。您必须IS NOT NULL

答案 1 :(得分:2)

我喜欢使用标准的SQL coalesce函数而非SQL Server的专有isnull来查找非空值,我们还可以使用nullif来满足“空白”要求:

select colpkey, coalesce(nullif(col1, ''), nullif(col2, ''), nullif(col3, ''), '') as col
from table_name1;

更新:

回答“我查询错误的地方?”并且如@ToddVrba所述,您不应该使用标准比较运算符(例如equals,less-than等)与null进行比较。它有助于将null视为关系数据库域中的“未知”,这意味着将已知值与未知值进行比较始终会产生未知值,或者为null。您应该使用is nullis not null

与null进行比较

此外,您的案例陈述过于复杂;你只需要一个案例陈述,如:

select colpkey, 
case when col1 is not null and col1 != '' then col1
     when col2 is not null and col2 != '' then col2
     when col3 is not null and col3 != '' then col3
     else '' end as col
from table_name1;

虽然我发现coalesce和nullif组合更简洁但同样可读。