0

错误:ORA-00937:不是单组组函数

询问:

    select count(*) todas,
       sum(case when i.prioridade = 1 then 1 else 0 end) urgente,
       sum(case when i.prioridade = 2 then 1 else 0 end) alta,
       sum(case when i.prioridade = 3 then 1 else 0 end) normal,
       sum(case when i.prioridade = 4 then 1 else 0 end) baixa,
       (select count(*)
        from GMITEMOS i 
        inner join GMCTLSLA c  on c.os = i.cd_numero_os and c.item = i.item
        where i.situacao in ('A', 'I', 'P')
           and c.ordem = 99999
           ) naoAvaliados,
       sum(case when i.situacao = 'P' then 1 else 0 end) pendentes,
       sum(case when i.situacao = 'A' or i.situacao = 'I' then 1 else 0 end) iniciados
from GMITEMOS i 
where i.situacao in ('A', 'I', 'P')
   and  exists (select 1 
               from GMCTLSLA c 
               where c.os = i.cd_numero_os 
                  and c.item = i.item)

错误发生在这里:

(select count(*)
        from GMITEMOS i 
        inner join GMCTLSLA c  on c.os = i.cd_numero_os and c.item = i.item
        where i.situacao in ('A', 'I', 'P')
           and c.ordem = 99999
           ) naoAvaliados

有人能说出为什么会这样吗?

4

3 回答 3

4

您可能已经修复了它,max但这不是它发生的原因,而且有点 hacky。您的问题是您的子查询(转换为单个列)不是聚合查询,,min等,因此需要包含在子句中。您通过将其包装来解决此问题,因为单个值的最大值将始终保持不变。maxsumgroup bymax

但是,由于您的子查询本身就是一个分析查询,并且只会返回一行,因此显而易见的事情是使用笛卡尔连接将其添加到您的查询中。在显式连接语法中,这称为cross join.

select count(*) todas
     , sum(case when i.prioridade = 1 then 1 else 0 end) urgente
     , sum(case when i.prioridade = 2 then 1 else 0 end) alta
     , sum(case when i.prioridade = 3 then 1 else 0 end) normal
     , sum(case when i.prioridade = 4 then 1 else 0 end) baixa
     , naoAvaliados
     , sum(case when i.situacao = 'P' then 1 else 0 end) pendentes
     , sum(case when i.situacao = 'A' or i.situacao = 'I' then 1 else 0 end) iniciados
  from GMITEMOS i 
 cross join (select count(*) as naoAvaliados
               from GMITEMOS j
              inner join GMCTLSLA k
                 on k.os = j.cd_numero_os 
                and k.item = j.item
              where j.situacao in ('A', 'I', 'P')
                and k.ordem = 99999
                    )
 where i.situacao in ('A', 'I', 'P')
   and exists (select 1 
                 from GMCTLSLA c 
                where c.os = i.cd_numero_os 
                  and c.item = i.item
                      )

笛卡尔连接的名声不好,因为它将连接一侧的行数乘以另一侧的行数。然而,它确实有它的用途,尤其是在这种情况下。

于 2012-07-05T18:10:04.033 回答
1

发生这种情况是因为子查询本身是标量结果,而不是组函数。正如您显然发现的那样,您可以通过替换一个产生与子查询等效结果的组函数来修复它。

于 2012-07-05T18:10:04.027 回答
0

在合并语句中,如果您遇到此错误而不是简单地使用 group by,它将解决问题。

merge into table1 tb1
using
   (select a.id,a.ac_no,sum(a.qy) as qyt,sum(a.amt) as sum_amt from 
    table2 a, table1 b
    where a.id=b.id
    and a.id = '1234'
    and a.date = '08Oct2014'
    and a.ac_no in (123, 234, 345)
    and a.ac_no = b.ac_no
    group by a.ac_no,a.id
   )qry
  on (qry.id=tb1.id and qry.ac_no=tb1.ac_no )
  when matched then
  update set qy=qry.qy,amt = qry.sum_amt;
于 2014-10-09T08:24:25.297 回答