简体   繁体   中英

use of min and count from 2 different table in ibm db2

How can i show which tutor teach the least subject?

桌子

this is my syntax but I'm getting

Error code 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

Expected output:

tut_id  subject_taught 
  id2          1

我没有可用的DB2,但现在据我可以看到在这里你就可以在DB2不能嵌套聚合函数:

$... min(count(session_code))...

This is pretty simple:

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)

SQL Fiddle Example


So what's going on in the statement?

First, the Common Table Expression ->

 WITH Subjects_Taught AS (SELECT tutor_id, COUNT(*) AS subjects_taught FROM Class GROUP BY tutor_id) 

This defines an in-query view or temporary table. These are handy for abstracting certain details away, or when you end up referring to the same info twice in a statement (as we do here). Essentially, you end up with a table that looks like this:

id1 | 2
id2 | 1
id3 | 2

... so then the only thing left is to restrict ourselves to rows of this table that meet the minimum:

 WHERE subjects_taught = (SELECT MIN(subjects_taught) FROM Subjects_Taught) 

... we reference our virtual table a second time, getting the minimum, as if it were a normal table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM