简体   繁体   中英

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM