我有一张如下表格
1,1@email.com,null
2,1@email.com,systemID2
3,2@email.com,null
4,2@email.com,null
5,3@email.com,systemID3
6,1@email.com,null
该表格中包含重复的电子邮件地址。在这些重复项中,有些具有' systemID' 我想要查询没有SystemID的所有重复项(只要其中一个重复项具有SystemID)
在此示例中,查询应仅提供两个结果:
1,1@email.com,null
6,1@email.com,null
答案 0 :(得分:1)
试试这个:
use tempdb
create table temp(
id int,
email varchar(100),
systemId varchar(100)
)
insert into temp
select 1,'1@email.com',null union all
select 2,'1@email.com','systemID2' union all
select 3,'2@email.com',null union all
select 4,'2@email.com',null union all
select 5,'3@email.com','systemID3' union all
select 6,'1@email.com',null
;with cte as(
select
*,
cc = count(*) over(partition by email)
from temp
)
select
t.*
from temp t
inner join cte c
on c.email = t.email
and c.cc > 1
and c.systemId is not null
where
t.systemId is null
order by email
drop table temp
答案 1 :(得分:0)
试试这个。
;WITH cte
AS (SELECT Count(1) cnt,a.email
FROM tablename a
JOIN tablename b
ON a.email = b.email
WHERE a.systemId IS NOT NULL
GROUP BY a.email
HAVING( Count(1) ) > 1)
SELECT b.id,b.email,b.systemId
FROM cte a
JOIN tablename b
ON a.email = b.email
WHERE b.systemId IS NULL