SQL组函数嵌套太深(SQL group function nested too deeply)

2019-11-02 03:52发布

我试图创建一个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);

Answer 1:

要做到这一点的方法之一是通过嵌套查询,然后选择输出的第一行:

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 。 此表似乎没有被使用(除非用于过滤的结果),并除去它implifies查询。



文章来源: SQL group function nested too deeply