[英]sql select records having count > 1 where at lease one record has value
I'm trying to get all participants that have more than 1 record in the table where at lease one of those records has IsCurrent = 0 and IsActive = 1 我试图让所有参与者在表中有超过1条记录,其中至少有一条记录的IsCurrent = 0且IsActive = 1
This is what I have so far, but it's not working: 这是我到目前为止,但它不起作用:
SELECT ParticipantId
FROM Contact
WHERE (IsCurrent = 0 AND IsActive = 1 AND ContactTypeId = 1)
Group by ParticipantId
Having COUNT(ParticipantId) > 1
This query brings back a record that matches that description, but I need all of the records that match that description, there are more. 此查询返回与该描述匹配的记录,但我需要与该描述匹配的所有记录,还有更多。
Use it as a subquery and join to it: 将其用作子查询并加入其中:
select * from
(
SELECT ParticipantId
FROM Contact
WHERE (IsCurrent = 0 AND IsActive = 1 AND ContactTypeId = 1)
Group by ParticipantId
Having COUNT(ParticipantId) > 1
) base
inner join Contact c on c.ParticipantId = base.ParticipantID
WHERE (IsCurrent = 0 AND IsActive = 1 AND ContactTypeId = 1)
select
ParticipantId
from Contact as c
group by
ParticipantId
having
Count(*) > 1
and
Sum(Case when IsCurrent = 0 then 1 else 0 end) >= 1
and
Sum(Case when IsActive = 1 then 1 else 0 end) >= 1
I would first try this 我会先试试这个
I think you should just remove: 我想你应该删除:
AND ContactTypeId = 1
which seems to be an idexed column 这似乎是一个独立的专栏
SELECT ParticipantId
FROM Contact
Group by ParticipantId
Having Count(*) > 1
Intersect
SELECT ParticipantId
FROM Contact
WHERE IsCurrent = 0
AND IsActive = 1
AND ContactTypeId = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.