'How to select non-NA values for each ID if present otherwise select NA in Oracle?
I have a df which can have single/several rows per ID. If it has multiple rows, only 1 row is populated with a non-NA value for a column. Sometimes all rows are NA. Using Oracle, I want to query out non-NA values if they exist otherwise the NA values as it is.
df:
ID Category
1 NA
1 A
1 NA
2 B
2 NA
3 NA
4 C
I want to have the following as the final result df.
df:
ID Category
1 A
2 B
3 NA
4 C
I tried joining with where clause non-NA but that is omiting ID 3.
Solution 1:[1]
Assuming there are not any nulls in the column category, for this sample data, you can use conditional aggregation:
select id,
coalesce(max(case when category <> 'NA' then category end), 'NA') category
from tablename
group by id
See the demo.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |