简体   繁体   English

查找没有“重复项”的记录

[英]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; 只需看一眼这些数据,您就可以清楚地看到Column1中具有BCD,EFG和FGH的记录没有任何其他重复项。 however, all other records look similar, except for the Column3 data. 但是,除Column3数据外,所有其他记录看起来都相似。

I could write a query to find these three records, but I only care about records that have "Z" in Column3. 我可以编写查询来查找这三个记录,但是我只关心Column3中具有“ Z”的记录。 This would result in the query only showing BCD and EFG, and not FGH. 这将导致查询仅显示BCD和EFG,而不显示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. 因此,我想要一个查询,该查询将查找记录,这些记录查找没有重复的记录(基于Column1和Column2),并且在Column3中具有“ Z”。

Any help is greatly appreciated! 任何帮助是极大的赞赏!

You can do this with aggregation and a having clause: 您可以使用聚合和having子句来做到这一点:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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