0

我正在尝试创建一个 sql 查询,该查询将返回出现在两个表之间的 id 的最小出现,但是我不断收到该行的错误HAVING MIN(COUNT(E.C_SE_ID))。Oracle 说按功能分组的嵌套太深。我想不出另一种返回方式 C_SE_ID

SELECT CS.C_SE_ID, MIN(COUNT(E.C_SE_ID))
FROM COURSE_SECTION CS, ENROLLMENT E, LOCATION L
WHERE CS.C_SE_ID=E.C_SE_ID
AND CS.LOC_ID=L.LOC_ID
AND L.BLDG_CODE='DBW'
GROUP BY CS.C_SE_ID
HAVING MIN(COUNT(E.C_SE_ID));

在招生表中s_idc_se_id已链接,我正在尝试获取与s_id此相关的所有内容c_se_id。使用更新的查询,oracle 不喜欢select *(出于明显的原因),但是当我也更改它时,我什么也e.c_Se_id得不到。

SELECT E.S_ID
FROM COURSE_SECTION CS, ENROLLMENT E
WHERE CS.C_SE_ID=E.C_SE_ID
AND E.C_SE_ID =(
select *
from (select CS.C_SE_ID, count(*) as cnt,
      max(count(*)) over (partition by cs.c_se_id) as maxcnt
      from COURSE_SECTION CS join
           ENROLLMENT E
           on CS.C_SE_ID=E.C_SE_ID join
           LOCATION L
           on CS.LOC_ID=L.LOC_ID
      where L.BLDG_CODE='DBW'
      GROUP BY CS.C_SE_ID
      order by count(*) desc
     ) t
where cnt = maxcnt);
4

1 回答 1

2

一种方法是嵌套查询,然后选择输出中的第一行:

select C_SE_ID, cnt
from (select CS.C_SE_ID, count(*) as cnt
      from COURSE_SECTION CS join
           ENROLLMENT E
           on CS.C_SE_ID=E.C_SE_ID join
           LOCATION L
           on CS.LOC_ID=L.LOC_ID
      where L.BLDG_CODE='DBW'
      GROUP BY CS.C_SE_ID
      order by count(*) desc
     ) t
where rownum = 1

on请注意,我使用而不是.将连接语法更新为更现代的版本where

如果您想要所有最小值(并且不止一个),那么我会使用分析函数。这与您的原始查询非常相似:

select *
from (select CS.C_SE_ID, count(*) as cnt,
             max(count(*)) over (partition by cs.c_se_id) as maxcnt
      from COURSE_SECTION CS join
           ENROLLMENT E
           on CS.C_SE_ID=E.C_SE_ID join
           LOCATION L
           on CS.LOC_ID=L.LOC_ID
      where L.BLDG_CODE='DBW'
      GROUP BY CS.C_SE_ID
      order by count(*) desc
     ) t
where cnt = maxcnt;

试试这个,而不是你原来的查询:

SELECT E.S_ID
FROM ENROLLMENT E
where E.C_SE_ID in (select C_SE_ID
                    from (select CS.C_SE_ID, count(*) as cnt,
                                 max(count(*)) over (partition by cs.c_se_id) as maxcnt
                          from ENROLLMENT E
                               LOCATION L
                               on CS.LOC_ID=L.LOC_ID
                          where L.BLDG_CODE='DBW'
                          GROUP BY e.C_SE_ID
                         ) t
                    where cnt = maxcnt)
                   );

除了修复连接之外,我还删除了所有对course_section. 该表似乎没有被使用(除非用于过滤结果),并且删除它意味着查询。

于 2013-05-15T23:02:03.670 回答