我需要一个SQL查询,该查询将允许我返回已完成列表中所有课程的值(学生)。
例如:
+-----+-------+---------+
| Key | Name | Course |
+-----+-------+---------+
| 1 | Mike | Maths |
| 2 | Dave | English |
| 3 | Chris | Science |
| 4 | Andy | Maths |
| 5 | Mike | German |
| 6 | Dave | Science |
| 7 | Chris | English |
| 8 | Chris | Maths |
| 9 | Dave | Maths |
+-----+-------+---------+
我需要列表中所有所有课程的学生姓名。该列表将随每个查询而变化。例如,我需要做过“英语”,“数学”和“科学”的人的名字,这些人将返回:
"Chris"
"Dave"
列表长度可以是任意数量的课程。输出将用于其他sql查询中,并且是更大项目的一部分,但是为了更容易理解,我已尝试尽可能简化问题。
我真的为如何实现这一目标而scratch之以鼻。任何帮助将不胜感激。
答案 0 :(得分:1)
您必须group by name
并将条件放在WHERE
和HAVING
子句中:
select name
from tablename
where course in ('English', 'Maths', 'Science')
group by name
having count(distinct course) = 3
答案 1 :(得分:-1)
我会考虑重新评估您的数据模型,但根据您提供的内容,这将是可行的。
基本解决方案:
SELECT Name
FROM Table T1
LEFT JOIN Table T2
ON T1.Name = T2.Name and T2.Course = 'Maths'
LEFT JOIN Table T3
ON T1.Name = T3.Name and T3.Course = 'English'
LEFT JOIN Table T3
ON T1.Name = T4.Name and T4.Course = 'Science'
WHERE T2.Course IS NOT NULL AND T3.Course IS NOT NULL AND T4.Course IS NOT NULL
更通用的解决方案:
SELECT Name, [English], [Science], [Maths], [German]
FROM Table
PIVOT (max(Course) FOR Name IN ([English],[Science],[Maths],[German])) AS Pivot
WHERE [English] IS NOT NULL AND [Science] IS NOT NULL AND [Maths] IS NOT NULL