3

I created a table like below. I want to select only NOT NULL column dynamically like(NO, NAME,SAL_1). No need to select SAL,SAL_2.

Note: Initially I don't know the columns values.

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;

data like below

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

Expected op:

NO       NAME   SAL_1
20      (null)  20
(null)  (null)  30
(null)  aaa     10
4
  • Select NO ,Name,SAL_1 from sample Commented Jul 4, 2017 at 11:10
  • @Velu: So total no. of columns, i.e. 5 columns, in your table will be fixed, right ? Commented Jul 4, 2017 at 11:48
  • @KeyurPanchal ..No columns is not fixed.In my table have 30 columns for sample purpose i given only 5. Commented Jul 4, 2017 at 12:37
  • probably repeat: stackoverflow.com/questions/21523338/… Commented Jul 6, 2017 at 19:12

3 Answers 3

0

The following query generates the query you want to execute through some dynamic SQL procedure.

Unfortunately I don't know well the Oracle syntax, the following is in PostgreSQL, but I guess you'll only have to change string_agg with the pertinent Oracle function catenating strings.

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;
Sign up to request clarification or add additional context in comments.

Comments

0

Try This,

I have checked and exactly match your output.

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

Comments

-1

Try This,

select * from sample where nvl(NO,0)> 0 and nvl(length(NAME),0)>0 and nvl(SAL_1,0)>0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.