简体   繁体   English

SQL为嵌套选择创建别名列?

[英]SQL Creating an Alias Column For a Nested Select?

Say I have a Person table and a Courses table. 假设我有一个Person表和一个Courses表。 In the Person table I have the column PersonName . Person表中,我有PersonName列。 In the Courses table, let's say I have CourseTitle , PersonName and CourseDifficulty . Courses表中,假设我有CourseTitlePersonNameCourseDifficulty CourseDifficulty is 1-4 (4 being the hardest). CourseDifficulty是1-4(4是最难的)。 How do I return a list of people from Person and for each person have a column that shows the most difficult class they're taking by CourseTitle . 如何从Person返回Person列表,并且每个人都有一个列,显示他们正在使用CourseTitle的最困难的课程。

As far as I know, I'd get the CourseTitle of the most difficult class Brett is taking by doing the following: 据我所知,我将通过以下方式获得Brett最困难的课程的课程标题:

SELECT CourseTitle 
FROM Courses 
WHERE PersonName = 'Brett' 
  AND CourseDifficulty = (SELECT MAX(CourseDifficulty) 
                          FROM Courses 
                          WHERE PersonName='Brett')

But how do I run that for each person in the Person table? 但是如何为Person表中的每个人运行它? I want the results to be something like 我希望结果是这样的

Brett-SQL For Dummies 4
Tim-Quantum Mechanics
Jane-Thermodynamics 2

Sorry for the noobness. 抱歉,这是一个noobness。 Thanks in advance for the help! 在此先感谢您的帮助!

you can use the following 你可以使用以下

SELECT p.name ,p.address, c.courseTitle ,c.courseDifficulty FROM (
        SELECT personName, courseTitle, MAX(courseDifficulty) AS courseDifficulty
        FROM course
        GROUP BY personName 
) AS c RIGHT JOIN person AS p ON p.name = c.personName

here am assuming personName is a unique. 这里假设personName是唯一的。 Otherwise you can use unique id over here instead on person name and add this field in select statement. 否则,您可以在此处使用唯一ID而不是人名,并在select语句中添加此字段。

Try this: 试试这个:

SELECT c.CourseTitle, c.PersonName, c.CourseDifficulty
  FROM Courses c
 WHERE c.CourseDifficulty=(SELECT MAX(c2.CourseDifficulty) FROM Courses c2 WHERE c2.PersonName=c.PersonName)

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

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