从两个字段中选择数据,只使用一个值

时间:2021-09-06 23:47:05

Let says i've data like below.

假设我有如下数据。

Col1    Col2
 A       E
 C       C   
         C
 D       
 G       C 

and output will be like below

输出如下所示

Column
  A    
  C       
  C    
  D       
  G     

So i want only take value that has a value, if that both columns has a value, take only from column1 only.

我只想取有值的值,如果两列都有值,只取列n1。

3 个解决方案

#1


3  

select nvl(col1,col2) from table1

NVL will check whether col1 is null if not it will take col1 value. If null it will take second col2 value

NVL将检查col1是否为null,否则取col1值。如果为空,则取第二个col2值

#2


2  

Also you could use CASE for common approach.

您还可以使用CASE作为通用方法。

SELECT CASE
     WHEN col1 IS NULL THEN col2
     ELSE col1
   END
FROM table1;

#3


1  

You could use COALESCE.

您可以使用合并。

For example,

例如,

SQL> WITH sample_data AS(
  2  SELECT 'A' col1, 'E' col2 FROM dual UNION ALL
  3  SELECT 'C' col1, 'C' col2 FROM dual UNION ALL
  4  SELECT '' col1, 'C' col2 FROM dual UNION ALL
  5  SELECT 'D' col1, '' col2 FROM dual UNION ALL
  6  SELECT 'G' col1, 'C' col2 FROM dual
  7  )
  8  SELECT COALESCE(col1, col2) val FROM sample_data;

V
-
A
C
C
D
G

SQL>

#1


3  

select nvl(col1,col2) from table1

NVL will check whether col1 is null if not it will take col1 value. If null it will take second col2 value

NVL将检查col1是否为null,否则取col1值。如果为空,则取第二个col2值

#2


2  

Also you could use CASE for common approach.

您还可以使用CASE作为通用方法。

SELECT CASE
     WHEN col1 IS NULL THEN col2
     ELSE col1
   END
FROM table1;

#3


1  

You could use COALESCE.

您可以使用合并。

For example,

例如,

SQL> WITH sample_data AS(
  2  SELECT 'A' col1, 'E' col2 FROM dual UNION ALL
  3  SELECT 'C' col1, 'C' col2 FROM dual UNION ALL
  4  SELECT '' col1, 'C' col2 FROM dual UNION ALL
  5  SELECT 'D' col1, '' col2 FROM dual UNION ALL
  6  SELECT 'G' col1, 'C' col2 FROM dual
  7  )
  8  SELECT COALESCE(col1, col2) val FROM sample_data;

V
-
A
C
C
D
G

SQL>