子查询 - 列出那些最多的

时间:2013-10-19 03:33:26

标签: sql oracle subquery

我正在尝试列出已经教授大多数Java课程的讲师教授的Java课程的讲师。

首先我选择教授java课程的讲师

SELECT z.FIRST_NAME,z.LAST_NAME,b.COURSE_NO, MAX(b.DESCRIPTION) AS DESCRIPTION
FROM INSTRUCTOR z
JOIN SECTION w ON z.INSTRUCTOR_ID = w.INSTRUCTOR_ID
JOIN COURSE b ON w.COURSE_NO = b.COURSE_NO
WHERE DESCRIPTION like '%Java%'
GROUP BY z.FIRST_NAME,z.LAST_NAME,b.COURSE_NO

它显示了我想要的结果

FIRST_NAME                LAST_NAME                  COURSE_NO DESCRIPTION                                      
 ------------------------- ------------------------- ---------- ---------------------------------
Tom                       Wojick                           120 Intro to Java Programming                          
Gary                      Pertez                           120 Intro to Java Programming                          
Anita                     Morris                           124 Advanced Java Programming                          
Todd                      Smythe                           122 Intermediate Java Programming                      
Charles                   Lowry                            122 Intermediate Java Programming                      
Charles                   Lowry                            120 Intro to Java Programming                          
Fernand                   Hanks                            122 Intermediate Java Programming                      
etc...

但是当我尝试选择教授最多Java课程的教师时,我得到了完全不同的结果

SELECT z.FIRST_NAME,z.LAST_NAME,b.COURSE_NO,b.DESCRIPTION
FROM INSTRUCTOR z
JOIN SECTION w ON z.INSTRUCTOR_ID = w.INSTRUCTOR_ID
JOIN COURSE b ON w.COURSE_NO = b.COURSE_NO
WHERE DESCRIPTION like '%Java%'
GROUP BY z.FIRST_NAME,z.LAST_NAME,b.COURSE_NO,b.DESCRIPTION
HAVING MAX(b.DESCRIPTION) =
(SELECT MAX(DESCRIPTION) 
FROM (
SELECT z.FIRST_NAME,z.LAST_NAME,b.COURSE_NO, MAX(b.DESCRIPTION) AS DESCRIPTION
FROM INSTRUCTOR z
JOIN SECTION w ON z.INSTRUCTOR_ID = w.INSTRUCTOR_ID
JOIN COURSE b ON w.COURSE_NO = b.COURSE_NO
WHERE DESCRIPTION like '%Java%'
GROUP BY z.FIRST_NAME,z.LAST_NAME,b.COURSE_NO
 )
 )
ORDER BY z.FIRST_NAME,z.LAST_NAME,b.COURSE_NO,b.DESCRIPTION;

我如何计算这些描述java课程并从中选择max,这样它只能向一位教师展示他所有的Java课程?

1 个答案:

答案 0 :(得分:2)

也许是这样的:

WITH q AS (
SELECT z.FIRST_NAME,z.LAST_NAME,b.COURSE_NO, MAX(b.DESCRIPTION) AS DESCRIPTION
     , COUNT(*) OVER (PARTITION BY z.FIRST_NAME, z.LAST_NAME) TheCount
  FROM INSTRUCTOR z
       JOIN SECTION w ON z.INSTRUCTOR_ID = w.INSTRUCTOR_ID
       JOIN COURSE b ON w.COURSE_NO = b.COURSE_NO
 WHERE UPPER(DESCRIPTION) like '%JAVA%'
 GROUP BY z.FIRST_NAME,z.LAST_NAME,b.COURSE_NO
)
SELECT first_name, last_name, course_no, description
  FROM q
 WHERE TheCount = (SELECT MAX(TheCount) FROM q);

请注意,这可能会为您提供多个教师。

另外,我比较了使用全部大写的课程描述搜索字符串,以消除由于JAVA处于不同情况而错过课程的可能性。

编辑:

有许多SQL函数可用作“分析”函数 - 其中函数应用于属于“窗口”的记录,即PARTITION BY子句。其中一些对排序也很敏感,也可以使用ORDER BY子句。您可以找到一些很好的参考资料here at Tim Hall's site。另一个是Shouvik Basu's blog