这是我当前的查询:
SELECT Takes_T.sec_id AS 'Section ID',
Takes_T.semester AS 'Semester',
Takes_T.year AS 'Year',
COUNT(Takes_T.takes_id) AS 'Enrollment'
From Takes_T
Group By Takes_T.year, Takes_T.semester, Takes_T.sec_id
ORDER BY Takes_T.year, Takes_T.semester DESC, Takes_T.sec_id,
Takes_T.course_id
;
这产生以下结果:
(我为糟糕的格式道歉。我无法弄清楚如何在表中得到这个)
Section ID | Semester | Year | Enrollment
1 | Spring | 2014 | 12922
2 | Spring | 2014 | 1434
3 | Spring | 2014 | 322
1 | Fall | 2014 | 12590
2 | Fall | 2014 | 2732
我需要做的是显示每个部分的MAX注册(部分是部分ID,学期和年份的组合)。所以我需要的是:
Section ID Semester Year Enrollment
1 Spring 2014 12922
1 Fall 2014 12590
如何修改查询以显示每个部分的MAX?
答案 0 :(得分:0)
我不知道您正在使用哪种RDBMS,但以下内容应与MS SQL Server一起使用:
SELECT
sec_id AS 'Section ID',
semester AS 'Semester',
year AS 'Year',
COUNT(takes_id) AS 'Enrollment'
FROM Takes_T t
WHERE sec_id = (
SELECT TOP 1 sec_id
FROM Takes_T
WHERE year = t.year
AND semester = t.semester
GROUP BY year, semester
ORDER BY count(*) DESC
)
GROUP BY year, semester, sec_id
ORDER BY year, semester DESC, sec_id
编辑:这对MySQL来说是一样的:
SELECT
sec_id AS 'Section ID',
semester AS 'Semester',
year AS 'Year',
COUNT(takes_id) AS 'Enrollment'
FROM Takes_T t
WHERE sec_id = (
SELECT sec_id
FROM Takes_T
WHERE year = t.year
AND semester = t.semester
GROUP BY year, semester
ORDER BY count(*) DESC
LIMIT 1
)
GROUP BY year, semester, sec_id
ORDER BY year, semester DESC, sec_id
答案 1 :(得分:0)
您可以执行嵌套选择:
SELECT max(Enrollment), SectionId, Semester, Year
FROM
(SELECT
Takes_T.sec_id AS 'SectionID',
Takes_T.semester AS 'Semester',
Takes_T.year AS 'Year',
COUNT(Takes_T.takes_id) AS 'Enrollment'
FROM Takes_T
GROUP BY Takes_T.year, Takes_T.semester, Takes_T.sec_id) a
GROUP BY SectionId, Semester, Year
答案 2 :(得分:0)
我明白了。这是我使用的代码:
SELECT Semester,
Year,
MIN(Enrollment) AS 'Min Enrollment',
MAX(Enrollment) AS 'Max Enrollment'
FROM(
SELECT Takes_T.sec_id AS 'Section_ID',
Takes_T.semester AS 'Semester',
Takes_T.year AS 'Year',
COUNT(Takes_T.takes_id) AS 'Enrollment'
From Takes_T
Group By Takes_T.year, Takes_T.semester, Takes_T.sec_id) MaxE
GROUP BY Year, Semester
ORDER BY Semester DESC
;
答案 3 :(得分:0)
如果可以使用临时表,可以试试这个:
CREATE TEMPORARY TABLE IF NOT EXISTS enrollment_count AS (
SELECT
sec_id,
semester,
year,
COUNT(takes_id) AS 'enrollment'
FROM Takes_T
GROUP BY year, semester, sec_id
);
SELECT
sec_id,
semester,
year,
enrollment
FROM enrollment_count ec
WHERE enrollment = (
SELECT MAX(enrollment)
FROM enrollment_count sub
WHERE sub.semester = ec.semester
AND sub.year = ec.year
)