oracle 在SQL中至少选择一个和两个

b5lpy0ml  于 2022-11-03  发布在  Oracle
关注(0)|答案(2)|浏览(213)

我有两个表student(ssn,name,major)transcript(ssn,grade)要返回什么查询
至少有一门课程成绩为A,主修计算机科学
至少有两门课程成绩为A,主修计算机科学。
对于一门课程,我尝试了下面的查询,但没有得到预期的结果
Select * from student s inner join transcript t on s.ssn = t.ssn where s.major = 'cs' and t.grade = 'A'
感谢你的帮助。

juud5qan

juud5qan1#

下面的嵌套查询可能对您的第二个问题有所帮助

SELECT
  s.ssn,
  s.name,
  s.major
FROM student s
INNER JOIN (
  SELECT 
    ssn,
    COUNT(grade) as number_of_A_grades
  FROM transcript
  WHERE grade = 'A'
  GROUP BY ssn
) A_grades_count
ON A_grades_count.ssn = s.ssn

WHERE A_grades_count.number_of_A_grades >= 2
ecfdbz9o

ecfdbz9o2#

您可以使用像ROW_NUMBER()这样的排名函数来避免使用聚合函数来实现此目的:

SELECT 
  a.ssn, 
  a.name, 
  a.major
FROM (SELECT 
        s.ssn, 
        s.name, 
        s.major,
        ROW_NUMBER() OVER (PARTITION BY s.ssn ORDER BY s.ssn ASC) AS rn
      FROM student s
      INNER JOIN transcript t ON s.ssn = t.ssn 
      WHERE t.grade = 'A' AND s.major = 'cs') a
WHERE a.rn >= 2
ORDER BY a.ssn ASC

小提琴

相关问题