How can I rewrite this t-sql to avoid using IN - and use joins in stead?
--Members with membership in 2008 but not in 2009, using IN and NOT IN
SELECT * FROM @Members
WHERE MemberId NOT IN
(SELECT MemberId FROM @Memberships WHERE [Year] = 2009) AND
MemberId IN (SELECT MemberId FROM @Memberships WHERE [Year] = 2008 )
I want to find people with a membership in 2008, who do not have a membership in 2009. The correct solution in the below example is George and Bill
Something like this...:
--Members with membership in 2008 but not in 2009, using IN and NOT IN
SELECT * FROM @Members m
INNER JOIN @Memberships msOld ON msOld.MemberId = m.MemberId AND [Year] = 2008
PLAYTHEMOFFKEYBOARDCAT JOIN @... HUh?
Complete schema to play with. :)
DECLARE @Members TABLE
(
MemberId INT,
Name VARCHAR(10)
)
INSERT INTO @Members VALUES (1, 'Joe')
INSERT INTO @Members VALUES (2, 'Mike')
INSERT INTO @Members VALUES (3, 'George')
INSERT INTO @Members VALUES (4, 'Bill')
INSERT INTO @Members VALUES (5, 'Kyle')
INSERT INTO @Members VALUES (6, 'Greg')
DECLARE @Memberships TABLE
(
MembershipId INT,
MemberId INT,
[Year] INT
)
INSERT INTO @Memberships VALUES (1, 1, 2009)
INSERT INTO @Memberships VALUES (2, 1, 2007)
INSERT INTO @Memberships VALUES (3, 1, 2006)
INSERT INTO @Memberships VALUES (4, 2, 2008)
INSERT INTO @Memberships VALUES (5, 2, 2009)
INSERT INTO @Memberships VALUES (6, 3, 2007)
INSERT INTO @Memberships VALUES (7, 3, 2008)
INSERT INTO @Memberships VALUES (8, 4, 2008)
INSERT INTO @Memberships VALUES (9, 5, 2007)
INSERT INTO @Memberships VALUES (10, 5, 2006)
INSERT INTO @Memberships VALUES (11, 5, 2005)
INSERT INTO @Memberships VALUES (12, 6, 2007)
--SELECT * FROM @Members m INNER JOIN @Memberships ms ON m.MemberId = ms.MemberId ORDER BY [Year]
--Membership in 2008
SELECT MemberId FROM @Memberships WHERE [Year] = 2008
--Members with no membership in 2009
SELECT * FROM @Members WHERE MemberId NOT IN
(SELECT MemberId FROM @Memberships WHERE [Year] = 2009)
--Members with membership in 2008 but not in 2009, using IN and NOT IN
SELECT * FROM @Members WHERE MemberId NOT IN
(SELECT MemberId FROM @Memberships WHERE [Year] = 2009) AND MemberId IN (SELECT MemberId FROM @Memberships WHERE [Year] = 2008 )
--Members with membership in 2008 but not in 2009, using IN and NOT IN
SELECT * FROM @Members m
INNER JOIN @Memberships msOld ON msOld.MemberId = m.MemberId AND [Year] = 2008