简体   繁体   中英

SQL Query with Sub-Query - Is there a better way?

for the 3 tables below

Student

StudentId, StudentName
1          aaa
2          bbb
3          ccc

Course

CourseId, CourseName
100       xxx
101       yyy
102       zzz

StudentCourse

StudentId, CourseID
1          100
1          101
2          100
2          102

To select all the courses for the first student alphabetically that attends course xxx, I could write the following query:

SELECT StudentName, CourseName
FROM Student
INNER JOIN StudentCourse ON Student.StudentId = StudentCourse.StudentID
INNER JOIN Course on StudentCourse.CourseID = Course.CourseID
WHERE StudentName in (
    SELECT TOP 1 StudentName 
    FROM Student 
    INNER JOIN StudentCourse on Student.StudentID = StudentCourse.StudentID
    INNER JOIN Course on StudentCourse.CourseID = Course.StudentID
    WHERE CourseName='xxx' 
    ORDER BY StudentName)

Is there a more efficient way of doing/writing this without the sub-select, because it appears I am doing the same query twice.

Thanks.

You can use window functions and top (1) with ties :

SELECT TOP (1) WITH TIES StudentName, CourseName
FROM (SELECT s.StudentName, c.CourseName,
             SUM(CASE WHEN c.CourseName = 'XXX' THEN 1 ELSE 0 END) OVER (PARTITION BY StudentName) as cnt_xxx
      FROM Student s INNER JOIN
           StudentCourse sc
           ON s.StudentId = sc.StudentID INNER JOIN
           Course c 
           ON sc.CourseID = c.CourseID
     ) sc
WHERE cnt_xxx > 0
ORDER BY StudentName;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM