简体   繁体   English

带子查询的SQL查询-有更好的方法吗?

[英]SQL Query with Sub-Query - Is there a better way?

for the 3 tables below 对于下面的3个表

Student 学生

StudentId, StudentName
1          aaa
2          bbb
3          ccc

Course 课程

CourseId, CourseName
100       xxx
101       yyy
102       zzz

StudentCourse 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: 要为第一个按字母顺序选择参加xxx课程的学生选择所有课程,我可以编写以下查询:

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 : 您可以将窗口函数和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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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