2

I have a query which loads data into a temporary table

SELECT * INTO #tempTable FROM Players where [reference month] = '2016-08-01' 

I now need to use these ID's to find them in the previous month

SELECT ID FROM Players WHERE [reference month] = '2016-07-01' AND EXISTS 
(SELECT #tempTable.ID FROM #tempTable)

I have tested the #tempTable (SELECT * FROM #tempTable) which returns 346 records which is correct.

The above code is searching every record (1000+) in the Players table and not the specific ID's that are found in the #tempTable

How can I fix this query to only use the ID's found in the #tempTable?

1
  • INNER JOIN or use IN rather than EXISTS Commented Oct 25, 2016 at 8:15

3 Answers 3

3

You may try any of the following options,

SELECT ID
FROM Players
WHERE [reference month] = '2016-07-01'
    AND EXISTS (
        SELECT T.ID
        FROM #tempTable T
        WHERE T.ID = Players.ID
    )

OR

SELECT P.ID
FROM Players P
INNER JOIN #tempTable T
    ON  T.ID = Players.ID
WHERE P.[reference month] = '2016-07-01'
Sign up to request clarification or add additional context in comments.

1 Comment

I went with the first option - and it worked - thanks
1

Try this

SELECT ID
FROM Players
WHERE [reference month] = '2016-07-01'
    AND ID IN (
        SELECT #tempTable.ID
        FROM #tempTable
    );

Comments

1

You are almost close. Just missing WHERE clause in EXISTS

SELECT ID FROM Players WHERE [reference month] = '2016-07-01' AND EXISTS 
(SELECT T.ID FROM #tempTable T WHERE T.ID = Players.ID)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.