如何检索热门项目的结果

时间:2015-02-05 14:13:29

标签: sql

我已经运行了一个查询,以便向我提供每所学校内的学生总数,但现在我需要知道每所学校内学生的姓名,同时保持最高结果总数位于顶部。如何添加到此查询以显示学生的姓名?

以下是我要向我展示每所学校的学生总数:

SELECT 
   dbo_Schools.Schools, 
   Count(dbo_tStudent.Student) AS NumberOfStudents
FROM 
   dbo_tStudent 
      INNER JOIN dbo_tSchools ON dbo_tStudent.SchoolID=dbo_tSchool.SchoolID
GROUP BY dbo_tSchool.School
ORDER BY Count(dbo_tStudent.Student) DESC;

重要的是,在列出学生的同时,让学生按照最多学生的顺序排列。

2 个答案:

答案 0 :(得分:1)

在这种情况下,您可以使用Sub Query来实现结果集。

要在子查询中使用order by,您还需要一个top or limit运算符。

SELECT sc.schoolname
    ,st.columns...
FROM dbo_tStudent st
INNER JOIN (
    SELECT TOP 1000 dbo_Schools.SchoolID
        ,min(schoolname) schoolname
        ,Count(dbo_tStudent.Student) AS NumberOfStudents
    FROM dbo_tStudent
    INNER JOIN dbo_tSchools ON dbo_tStudent.SchoolID = dbo_tSchools.SchoolID
    GROUP BY dbo_tSchool.School
    ORDER BY Count(dbo_tStudent.Student) DESC
    ) sc ON st.SchoolID = sc.SchoolID

答案 1 :(得分:0)

假设您使用的是SQL Server,您可以使用CTE加入第一个聚合,其中包含以下详细信息:

;WITH cte as (
    SELECT TOP 1000 dbo_Schools.SchoolID, Count(dbo_tStudent.Student) AS NumberOfStudents
    FROM 
        dbo_tStudent 
            INNER JOIN dbo_tSchools ON dbo_tStudent.SchoolID = dbo_tSchools.SchoolID
    GROUP BY dbo_tSchool.School
    ORDER BY Count(dbo_tStudent.Student) DESC
)

SELECT
    sc.<your school name column>,
    st.<your student columns>
from
    dbo_tStudent st
        INNER JOIN cte ON st.SchoolID = cte.SchoolID
        INNER JOIN dbo_tSchools sc on cte.SchoolID = sc.SchoolID

更一般地说:您需要一个derived table(包含group by子句的聚合),它与学生详细信息的select语句一起加入。在此示例中,CTE基本上是SQL Server功能,便于使用派生表。