Sesame
Sesame

Reputation: 3410

Find records that do not have "duplicates"

I am trying to find records in a table which do not have "duplicates" based on a certain criteria. I put duplicates in quotes because these records are not literal duplicates, as I my example data will show.

MyTable
Column1-----Column2-----Column3
ABC---------123---------A
ABC---------123---------Z
BCD---------234---------Z
CDE---------345---------A
CDE---------345---------Z
DEF---------456---------A
DEF---------456---------Z
EFG---------567---------Z
FGH---------678---------A

Just glancing at this data, you can clearly see that the records with BCD, EFG, and FGH in Column1 do not have any additional duplicates; however, all other records look similar, except for the Column3 data.

I could write a query to find these three records, but I only care about records that have "Z" in Column3. This would result in the query only showing BCD and EFG, and not FGH.

So, I would like a query that will find records that find records that do not have duplicates (based on Column1 and Column2) and that have "Z" in Column3.

Any help is greatly appreciated!

Upvotes: 2

Views: 66

Answers (2)

smoore4
smoore4

Reputation: 4866

Different syntax, same result.

SELECT A.column1, A.column2
FROM MyTable A
LEFT JOIN MyTable B ON A.column1= B.column1AND A.column2= B.column2
WHERE A.column3 = 'z'
GROUP BY A.column1, A.column2
HAVING COUNT(*) = 1

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269483

You can do this with aggregation and a having clause:

select column1, column2, max(column3)
from mytable
group by column1, column2
having count(*) = 1 and max(column3) = 'Z';

Upvotes: 5

Related Questions