Jay Jay - 5 months ago 16
SQL Question

SQL How to find non repeating sub category based on the main category

Have a table with 3 columns. ID, Main and Sub1
I want to write a query where it will select strings in the Sub1 column if the Main column is unique. So for example text in Sub1 can be the exact same word but the word in the Main column is different and it will show both records. Please see pic
enter image description here


You seem to almost want:

select distinct main, sub1
from t
where sub1 is not null;

But, the id gets in the way. So, use group by instead:

select min(id) as id, main, sub1
from t
where sub1 is not null
group by main, sub1;

Note: This assumes that the empty values of sub1 are NULL. If they are empty strings, then use where sub1 <> ''.