如何将oracle sql中的多个列连接成单个列,仅用于匹配条件

时间:2018-01-09 18:53:23

标签: sql oracle

我有4列以下

      empid | name  | dept     | ph_no
      ---------------------------------
      123   | null  |  null    | null
      124   | mike  |  science | null
      125   | null  |  physics | 789
      126   | null  |  null    | 463
      127   | john  |  null    | null

我需要将所有4列合并为单列,仅用于空值。 我需要下面的东西 -

    empid
 ------------
  123 is missing name,dept,ph_no
  124 is missing ph_no
  125 is missing name
  126 is missing name,dept
  127 is missing dept,ph_no

3 个答案:

答案 0 :(得分:1)

可以使用case表达式完成此操作。

select empid,empid||' is missing '|| 
trim(',' from 
     (case when name is null then 'name,' else '' end||
      case when dept is null then 'dept,' else '' end||
      case when ph_no is null then 'ph_no' else '' end
     )
     ) 
from tbl

答案 1 :(得分:1)

我同意Vamsi并且只想添加一个where子句,以便不会返回“完整”子句。

select empid,empid||' is missing '|| 
       case when name is null then 'name,' else '' end||
       case when dept is null then 'dept,' else '' end||
       case when ph_no is null then 'ph_no' else '' end
 from tbl
where (name is null or dept is null or ph_no is null);

答案 2 :(得分:1)

您也可以使用NVL2功能。

SELECT empid||' is missing '||NVL2(name, NULL, 'name, ') ||NVL2(dept, NULL, 'dept, ')||NVL2(ph_no, NULL, 'ph_no') empid
  FROM table_