我想列出教授“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
答案 0 :(得分:1)
这个查询怎么样,我还没试过,但是:
SELECT i.I_FNAME, COUNT(f.I_ID) as Cnt, MAX(f.CO_TERMNUMBER), MAX(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'
GROUP BY i.I_FNAME
答案 1 :(得分:0)
If you have aggeragate function then use having statement like and must below order :
select * from table
where cond...
group by ...
having cond ...
order by..
=======================
Exapmle:
SELECT t.I_ID, i.I_FNAME, COUNT(f.I_ID) as Cnt, f.CO_TERMNUMBER, f.CO_YEAR
FROM
INSTRUCTOR i
left outer JOIN TEACHINGQUALIFICATION t ON i.I_ID = t.I_ID
left outer JOIN COURSE c ON c.C_ID = t.C_ID
left outer JOIN COURSEOFFERING f ON i.I_ID = f.I_ID
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
答案 2 :(得分:0)
您需要使用Having clause
尝试这个(我没有测试过)
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'
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