我如何向哪位导师讲授最少的科目?
这是我的语法,但我正在
错误代码42607
select
tut_id,
min(count(session_code)) as subject_taught
from
tutor,
class
where
tutor.tutor id = class.tut_id
group by tut_id
预期产出:
tut_id subject_taught
id2 1
答案 0 :(得分:0)
我现在没有DB2可用,但据我所知here,您无法在DB2中嵌套聚合函数:
$... min(count(session_code))...
答案 1 :(得分:0)
这很简单:
WITH Subjects_Taught AS (SELECT tutor_id, COUNT(*) AS subjects_taught
FROM Class
GROUP BY tutor_id)
SELECT tutor_id, subjects_taught
FROM Subjects_Taught
WHERE subjects_taught = (SELECT MIN(subjects_taught)
FROM Subjects_Taught)
<小时/>
那么声明中发生了什么?
首先,公用表表达式 - &gt;
WITH Subjects_Taught AS (SELECT tutor_id, COUNT(*) AS subjects_taught
FROM Class
GROUP BY tutor_id)
这定义了查询中的视图或临时表。这些对于抽象某些细节很方便,或者当你最终在一个语句中引用相同的信息两次时(就像我们在这里所做的那样)。从本质上讲,您最终会得到一个如下所示的表:
id1 | 2
id2 | 1
id3 | 2
...所以剩下的就是将自己限制在符合最低要求的这个表行中:
WHERE subjects_taught = (SELECT MIN(subjects_taught)
FROM Subjects_Taught)
...我们第二次引用我们的虚拟表,得到最小值,好像它是一个普通的表。