1

Given two tables 'Draws' (id, date) AND 'Results' (id, draw_id, number) where each Draw has x results, how can I get the draws that have a subgroup of numbers within their results?

Draws
-----------------
Id | Date
-----------------
1  | 2015-01-20
2  | 2015-01-22
-----------------

Results
--------------------
Id  | Draw | Number
--------------------
1   | 1    | 13
2   | 1    | 15
3   | 1    | 22
4   | 1    | 36
5   | 1    | 45
6   | 2    | 11
7   | 2    | 15
8   | 2    | 22

How can I get the draw that has (15,22,45) within its results? (In the example draw #1)

timss
  • 9,982
  • 4
  • 34
  • 56

5 Answers5

1

Good catch by Fred, this will return the correct results:

SELECT
    d.*
FROM
    Draw AS d
INNER JOIN Results AS r1 ON r1.Draw = d.ID AND r1.Number = 15
INNER JOIN Results AS r2 ON r2.Draw = d.ID AND r2.Number = 22
INNER JOIN Results AS r3 ON r3.Draw = d.ID AND r3.Number = 45
GROUP BY
    d.id;

Fred's answer will work, but tbh it's fragile in that it will only work if you are looking for 3 results. My answer is more deliberate, however you will have to construct the query programatically to determine how many joins are necessary to get the results you want, for example:

15 -> 1 join
15, 22 -> 2 joins
15, 22, 45 -> 3 joins
....
Mike Purcell
  • 19,847
  • 10
  • 52
  • 89
0

Per your question you don't need a join or anything...

select Draw from 
Results r
where r.Number in (15,22,45);
FirebladeDan
  • 1,069
  • 6
  • 14
0

This is another possibility (without duplicates)

select * from Draws d where exists (select * from Results r where r.Draw=d.Id and Number in (1, 2, 3...) );
marian0
  • 664
  • 6
  • 15
0

You just need to use JOIN for getting this result

SELECT * FROM Draw, Results 
WHERE Draw.ID = Results.DrawID 
AND Results.Number IN (15,22,45);

In Result:

You will get the Results ids (2, 3, 5, 7, 8)

devpro
  • 16,184
  • 3
  • 27
  • 38
0
SELECT Draw FROM Results
Where Number IN (15,22,45)
Group By Draw
Having Count(*) > 2

Will give you only Draws that have all 3

SELECT d.Date, r.Draw FROM #result r Join #Draws d ON d.id = r.Draw
Where Number IN (15,22,45)
Group By d.Date, r.Draw
Having Count(*) > 2

If you want the date in the results.

Fred
  • 5,663
  • 4
  • 45
  • 74