Jay Jay - 1 year ago 86
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

Answer Source

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 <> ''.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download