Reputation: 317
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
Upvotes: 0
Views: 88
Reputation: 14858
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
Upvotes: 1
Reputation: 133400
You can use an aggregate function max and group by
select id, sd, max(feed)
from my_table
group by id, sd;
Upvotes: 2