2012-07-05 44 views
0

錯誤:ORA-00937:不是單組分組函數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) 

錯誤在這裏ocurring :

(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 

有人可以告訴爲什麼會發生?

+1

嘗試將單列放入組中,而不是將它分組爲不同的東西 – Jester 2012-07-05 17:40:55

+0

只需使用max()修復它,謝謝。 – 2012-07-05 17:46:25

回答

4

您可能已經修復它與max但這不是爲什麼它的發生,有點hacky。你的問題是,你的子查詢翻譯成單個列不是聚合查詢,min,max,sum等等,因此需要包含在group by子句中。您通過將其包裝在max中來解決此問題,因爲單個值的最大值將始終保持不變。

但是,由於您的子查詢本身是一個分析查詢,並且只會返回一行,所以顯而易見的做法是使用笛卡爾連接將其添加到查詢中。在顯式連接語法中,這被稱爲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 
        ) 

笛卡爾連接的信譽很差,因爲它將連接一側的行數乘以另一側的行數。但是,它的確有用,特別是在這種情況下。

1

這是因爲子查詢本身是標量結果而不是組函數。正如你明顯發現的那樣,你可以通過用一個產生與你的子查詢等價的結果的組函數來修復它。

0

在merge語句中,如果出現此錯誤而不是簡單地使用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;