选择唯一的MemberID

时间:2017-05-30 14:01:42

标签: sql-server

我有一张桌子[VotingStatusHistory] ​​

[MemberID] | [AffilliationDate]

相同MemberID可以有多个AffilliationDates

31009 - 2011-04-28    
31009 - 2010-04-28    
31009 - 2009-04-28    
31009 - 2008-04-28    
31009 - 2007-04-28    
31009 - 2006-04-28

现在我想选择只有2006年AffilliationDates记录的会员ID。

提前致谢

5 个答案:

答案 0 :(得分:1)

使用NOT IN ...

SELECT  *
FROM    VotingStatusHistory 
WHERE   DATEPART(year,AffiliationDates) = 2006
AND MemberID NOT IN (SELECT MemeberID FROM VotingStatusHistory WHERE DATEPART(year,AffiliationDates) <> 2006) 

答案 1 :(得分:0)

你可以这样使用NOT EXISTS

SELECT  *
FROM    VotingStatusHistory T1
WHERE   YEAR(T1.AffiliationDates) = 2006
    AND NOT EXISTS (
                        SELECT      NULL
                        FROM        VotingStatusHistory T2
                        WHERE       YEAR(T2.AffiliationDates) <> 2006
                                AND T1.MemberID = T2.MemberID
                    )

答案 2 :(得分:0)

使用except集合运算符。为什么没人学习这些?

select vs.MemberID from dbo.VoterStatusHistory as vs 
where vs.AffiliationDate >= '20060101' and vs.AffiliationDate < '20070101'
except 
select vs.MemberID from dbo.VoterStatusHistory as vs 
where vs.AffiliationDate < '20060101' or vs.AffiliationDate >= '20070101'

答案 3 :(得分:-1)

你看这个吗?

Select * from yourtable where year(AffiliationDates) = 2006

答案 4 :(得分:-1)

select MemberID,
from VotingStatusHistory
group by MemberID
having sum(case when year(AffilliationDate)=2006 then 0 else 1 end)=0