kamojoe
kamojoe

Reputation: 53

How do I only select records in a table that have all the values from another table?

This is a hard question to word, but is pretty simple when explained a little more.

I have two tables: Standard_Test{StandardID int, TestID int} and Test{TestID int}

Standard_Test: http://i51.tinypic.com/2u60ket.png

Test: http://i51.tinypic.com/2bbqxj.png

I need to select a list of StandardID's that have all of the TestID's from the Test table associated to it. In the example above, this query would only select StandardID 5 & 6 because they both have TestID's 1,2,3(all of the TestID's from Test) associated with it.

It sounds simple, but I have not been able to come up with the proper query. Thanks in advanced!

Upvotes: 1

Views: 118

Answers (4)

Sanjay
Sanjay

Reputation: 342

The Below Code will Work To find your Requirement. Check it out. Here Tab1 = Standard_Test And tab2 = Test

Declare @Test Int

Declare @Tab table ( Stand int )

Declare @Cur Cursor Set @Cur = CURSOR For Select standardID From tab1 Group by standardID

Open @Cur Fetch Next From @Cur into @Test

WHILE @@FETCH_STATUS = 0
    Begin
        If Exists (Select 1
        From tab2
        Where estID not in (Select testId From tab1 Where StandardID = @Test))
            Begin
                insert into @Tab
                values(@Test)
            End
        Fetch Next
        From @Cur into @Test
    End

Close @Cur DEALLOCATE @Cur

Select * From @Tab

Upvotes: 0

Marco
Marco

Reputation: 57573

You could try this, it should work:

SELECT DISTINCT st.StandardId
FROM Standard_Test st JOIN Test t
ON st.TestId = t.TestId    
GROUP BY st.StandardId
HAVING COUNT(st.TestId) = (SELECT COUNT(TestId) FROM Test)

Upvotes: 2

Erwin Smout
Erwin Smout

Reputation: 18408

This is relational division. Google for that term and you should find all the info you need.

Upvotes: 1

Philip Kelley
Philip Kelley

Reputation: 40309

This should work for any number of rows in Test. (It assumes that a given TestId only appears once in Test -- it is the primary key, right?)

SELECT st.StandardID
 from Standard_Test st
  inner join Test te
   on te.TestID = st.TestID
 group by st.StandardID
 having count(te.TestId) = (select count(*) from Test)

Upvotes: 1

Related Questions