2010-04-21 21 views
1

這個查詢提供了一個錯誤:我不能用SUM函數此查詢工作

select ep, 
    case 
    when ob is null and b2b_ob is null then 'a' 
    when ob is not null or b2b_ob is not null then 'b' 
    else null 
    end as type, 
    sum(b2b_d + b2b_t - b2b_i) as sales 
from table 
where ... 
group by ep, type 

錯誤:ORA-00904: 「TYPE」:無效的標識符

當我與group by ep運行它,錯誤消息變成:

ORA-00979:不是GROUP BY表達式

如果刪除線,整個查詢工作OK sum(b2b_d+b2b_t-b2b_i) as salesgroup by ...,所以問題應該與SUM和GROUP BY函數有關。我該如何做這項工作?在此先感謝您的幫助。

回答

4

不幸的是SQL不允許你使用的列別名在GROUP BY子句中,所以你要麼必須有重複整個案件是這樣的:

select ep, 
    case 
    when ob is null and b2b_ob is null then 'a' 
    when ob is not null or b2b_ob is not null then 'b' 
    else null 
    end as type, 
    sum(b2b_d + b2b_t - b2b_i) as sales 
from table 
where ... 
group by ep, 
    case 
    when ob is null and b2b_ob is null then 'a' 
    when ob is not null or b2b_ob is not null then 'b' 
    else null 
    end 

或使用在線查看樣這:

select ep, 
    type, 
    sum(b2b_d + b2b_t - b2b_i) as sales 
from 
(select ep, 
    case 
     when ob is null and b2b_ob is null then 'a' 
     when ob is not null or b2b_ob is not null then 'b' 
     else null 
    end as type, 
    b2b_d, 
    b2b_t, 
    b2b_i 
    from table 
    where ... 
) 
group by ep, type 
+0

現在它的工作。非常感謝。 – 2010-04-21 08:52:36