如何动态选择非空值列?

时间:2017-07-04 11:01:07

标签: sql oracle oracle11g

我创建了一个如下表格。我想动态选择NOT NULL列(NO,NAME,SAL_1)。无需选择SAL,SAL_2。

注意:最初我不知道列值。

create table sample(no integer,name varchar(20),sal integer,sal_1 integer,sal_2 integer);
insert into sample(name,sal_1) values('aaa',10);
insert into sample(no,name,sal_1) values(20,'',20);
insert into sample(sal_1) values(30);

select * from sample;

以下数据

NO        NAME    SAL   SAL_1 SAL_2
20       (null)   (null)  20  (null)
(null)    (null)  (null)  30  (null)
(null)    aaa     (null)  10  (null)

预期的操作:

NO       NAME   SAL_1
20      (null)  20
(null)  (null)  30
(null)  aaa     10

3 个答案:

答案 0 :(得分:0)

以下查询生成您要通过某个动态SQL过程执行的查询。

不幸的是我不太了解Oracle语法,以下是在PostgreSQL中,但我想你只需要用相关的Oracle函数链接字符串来改变string_agg

WITH columns (c) AS (
  SELECT 'no' WHERE EXISTS (SELECT * FROM sample WHERE no IS NOT NULL)
  UNION
  SELECT 'name' WHERE EXISTS (SELECT * FROM sample WHERE name IS NOT NULL)
  UNION
  SELECT 'sal' WHERE EXISTS (SELECT * FROM sample WHERE sal IS NOT NULL)
  UNION
  SELECT 'sal_1' WHERE EXISTS (SELECT * FROM sample WHERE sal_1 IS NOT NULL)
  UNION
  SELECT 'sal_2' WHERE EXISTS (SELECT * FROM sample WHERE sal_2 IS NOT NULL)
)
SELECT 'SELECT ' || string_agg(c, ', ') || ' FROM sample;' FROM columns;

答案 1 :(得分:0)

试试这个,

我已检查并完全匹配您的输出。

    
select no,"NAME",sal_1 from sample having count(sal_1)>0  group by 
sal_1,name,no order by name desc 

答案 2 :(得分:-1)

试试这个,     

从样本中选择*,其中nvl(NO,0)> 0和nvl(长度(NAME),0)> 0和nvl(SAL_1,0)> 0