首页 > 解决方案 > 选择一组学生的 SQL 查询,他们的学年开始和结束日期包含另一个表中的开始和结束日期?

问题描述

迅速的:

谁是让多洛雷斯·乌姆里奇担任 DADA 老师的格兰芬多学生(假设所有学生都参加 DADA,并且所有学生从秋季开始到春季结束的整个学年都在学校,请记住,列出的每位 DADA 老师都是从秋季开始的并离开了下一个春天)?

DADA table

  last    |  first   | start | finish 
----------+----------+-------+--------
 Quirrell | Quirinus |  1991 |   1992
 Lockhart | Gilderoy |  1992 |   1993
 Lupin    | Remus    |  1993 |   1994
 Moody    | Alastor  |  1994 |   1995
 Umbridge | Dolores  |  1995 |   1996
 Snape    | Severus  |  1996 |   1997
 Carrow   | Amycus   |  1997 |   1998

Students table 

 last            |   first    |   house    | start | finish 
-----------------+------------+------------+-------+--------
 Abbott          | Hannah     | Hufflepuff |       |       
 Abercrombie     | Euan       | Gryffindor |  1995 |       
 Ackerley        | Stewart    | Ravenclaw  |  1994 |       
 Astoria         | Greengrass | Slytherin  |       |       
 Baddock         | Malcolm    | Slytherin  |  1994 |       
 Bell            | Katie      | Gryffindor |  1990 |   1997
 Black           | Bellatrix  | Slytherin  |  1962 |       
 Black           | Narcissa   | Slytherin  |  1966 |   1973
 Black           | Phineas    | Slytherin  |       |       
 Black           | Regulus    | Slytherin  |  1972 |       
 Black           | Sirius     | Gryffindor |  1971 |   1978
 Bletchley       | Miles      | Slytherin  |       |       
 Bones           | Susan      | Hufflepuff |  1991 |   1998
 Boot            | Terry      | Ravenclaw  |  1991 |   1998
 Branstone       | Eleanor    | Hufflepuff |  1994 |       
 Brocklehurst    | Mandy      | Ravenclaw  |  1991 |       
 Brown           | Lavender   | Gryffindor |  1991 |   1998
 Bulstrode       | Millicent  | Slytherin  |  1991 |       

尝试使用 WITH 子查询,但只获取与 Delores Umbridge 相同开始年份的学生,而不是让她成为 DADA 老师的 6 年级学生。任何提示表示赞赏。

标签: sql

解决方案


据我了解,这就是您想要的:

select a.* from Students a inner join DADA b
on a.start <= b.start and coalesce(a.finish, 2999) >= b.finish 
where b.last = 'Umbridge' and b.first = 'Dolores'  
and house = 'Gryffindor'

推荐阅读