SQL组函数嵌套得太深了

时间:2013-05-15 22:56:12

标签: sql oracle group-by having

我正在尝试创建一个sql查询,该查询将返回两个表之间出现的最小出现的id但是我一直收到行HAVING MIN(COUNT(E.C_SE_ID))的错误。甲骨文说,按功能分组太深了。 我想不出另一种回归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);

1 个答案:

答案 0 :(得分: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的所有引用。似乎没有使用此表(除非用于过滤结果),并且删除它会使查询失效。