我想列出教“java”的教授的名字,他教的次数以及他教的最近一年和学期。
我尝试了这个查询,但它给出了两行具有相同名称的行。
SELECT i.I_FNAME, COUNT(f.I_ID) as myCount, f.CO_TERMNUMBER, f.CO_YEAR
FROM
INSTRUCTOR i
JOIN TEACHINGQUALIFICATION t
ON i.I_ID = t.I_ID
JOIN COURSE c
ON c.C_ID = t.C_ID
JOIN COURSEOFFERING f
ON i.I_ID = f.I_ID
WHERE c.C_TITLE = 'java'
GROUP BY t.I_ID, i.I_FNAME, f.CO_TERMNUMBER, f.CO_YEAR
ORDER BY f.CO_YEAR desc
输出:
1 Gaurav 1 4 2006
2 Gaurav 1 1 2000
预期输出:
1 Gaurav 2 4 2006
有错误的代码:
我还使用条件“AND f.CO_YEAR = MAX (f.CO_YEAR)”尝试了此代码,但它显示此错误“此处不允许使用组函数”
SELECT t.I_ID, i.I_FNAME, COUNT(f.I_ID) as Cnt, f.CO_TERMNUMBER, f.CO_YEAR
FROM
INSTRUCTOR i
JOIN TEACHINGQUALIFICATION t
ON i.I_ID = t.I_ID
JOIN COURSE c
ON c.C_ID = t.C_ID
JOIN COURSEOFFERING f
ON i.I_ID = f.I_ID
WHERE c.C_TITLE = 'itec801' AND f.CO_YEAR= MAX (f.CO_YEAR)
GROUP BY t.I_ID, i.I_FNAME, f.CO_TERMNUMBER, f.CO_YEAR
ORDER BY f.CO_YEAR desc
更新
此代码显示最新年份的输出,但问题是当它获取最新行时,计数器停在那里并显示 1 个值。但我想计算所有行,然后只显示最近一年。
SELECT t.I_ID, i.I_FNAME, COUNT(f.I_ID) as Cnt, f.CO_TERMNUMBER, f.CO_YEAR
FROM
INSTRUCTOR i
JOIN TEACHINGQUALIFICATION t
ON i.I_ID = t.I_ID
JOIN COURSE c
ON c.C_ID = t.C_ID
JOIN COURSEOFFERING f
ON i.I_ID = f.I_ID
JOIN
(
SELECT I_ID, MAX(CO_YEAR) LatestYear
FROM COURSEOFFERING GROUP BY I_ID
)
f2 ON f.I_ID = f2.I_ID AND f.CO_YEAR = f2.LatestYear
WHERE c.C_TITLE = 'itec801'
GROUP BY t.I_ID, i.I_FNAME, f.CO_TERMNUMBER, f.CO_YEAR
having f.CO_YEAR= MAX (f.CO_YEAR)
ORDER BY f.CO_YEAR desc
新输出:
1 Gaurav 1 4 2006
预期输出:
1 Gaurav 2 4 2006