0
votes

I have a table and in this table there are sometimes single or duplicate lines with 1 different attribute. This attribute is typically either null or with a value. How can I write a select statement to return all without duplicates and pick the data that has the value and where it doesnt, then return the attribute for null.

e.g.

ID   SD     FEED
0016 21AE   GF-HF   
0016 21AE   null
0017 21BE   FF-HF   
0017 21BE   null
0018 21CE   CF-HF   
0018 21CE   null
0019 21DE   null    
0019 21DE   null

Should return from the select statement: (no duplicates)

ID   SD     FEED
0016 21AE   GF-HF   
0017 21BE   FF-HF   
0018 21CE   CF-HF   
0019 21DE   null    
2
which value should be picked up when the attribute is not null? - Vamsi Prabhala
Have you tried something already? What about if doesn't work? - Lexi
select id,sd,max(FEED) from yourtable group by id,sd - Maheswaran Ravisankar
@MaheswaranRavisankar, this doesnt pull everything. If you look at the question above, I am trying to pull all including null's where there is no value. - No Body
select id, sd, max(nvl(feed, ' ')) feed from yourtable group by id, sd. - T Gray

2 Answers

2
votes

You can use an aggregate function max and group by

select id, sd, max(feed) 
from my_table
group by id, sd;
1
votes
select distinct id, sd, feed
  from (select id, sd, feed, max(feed) over(partition by id, sd) as mf from t)
 where (feed is not null and mf is not null)
    or (feed is null and mf is null)
 order by id, sd, feed

I understood, that you want all distinct values of FEED for each combination of (ID, SD) and nulls only when no other value exists. Instead of max() you can use min() in analytic version.

Test:

create table t ( ID varchar2(10), SD varchar2(10), FEED varchar2(10));
insert into t values (0016, '21AE', 'GF-HF' );
insert into t values (0016, '21AE', 'GF-HF' );
insert into t values (0016, '21AE', 'AF-AF' );
insert into t values (0016, '21AE', null );
insert into t values (0017, '21BE', 'FF-HF' );
insert into t values (0017, '21BE', null );
insert into t values (0018, '21CE', 'CF-HF' );
insert into t values (0018, '21CE', null );
insert into t values (0019, '21DE', null );
insert into t values (0019, '21DE', null );

ID         SD         FEED
---------- ---------- ----------
16         21AE       AF-AF
16         21AE       GF-HF
17         21BE       FF-HF
18         21CE       CF-HF
19         21DE