SELECT 值子组

SELECT subgroup of values

给定两个表格 'Draws' (id, date) AND 'Results' (id, draw_id, number) 其中每个抽奖有 x 个结果,我怎样才能得到在他们的抽奖中有一个数字子组的抽奖结果?

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

如何获得结果中包含 (15,22,45) 的抽奖? (在抽奖#1 的例子中)

根据你的问题,你不需要加入或任何东西...

select Draw from 
Results r
where r.Number in (15,22,45);

Fred 抓得好,这将 return 正确的结果:

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 的答案会起作用,但它很脆弱,因为它只有在您寻找 3 个结果时才起作用。我的回答是经过深思熟虑的,但是您必须以编程方式构建查询以确定需要多少个连接才能获得所需的结果,例如:

15 -> 1 join
15, 22 -> 2 joins
15, 22, 45 -> 3 joins
....

这是另一种可能性(没有重复)

select * from Draws d where exists (select * from Results r where r.Draw=d.Id and Number in (1, 2, 3...) );

您只需使用 JOIN 即可获得此结果

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

结果:

您将获得结果 ID (2, 3, 5, 7, 8)

SELECT Draw FROM Results
Where Number IN (15,22,45)
Group By Draw
Having Count(*) > 2

只会给你全部 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

如果您想要结果中的日期。