2012-11-12 121 views
-7

我在oracle中有一個sql表,如下所示,它的名字就是範圍。以表格格式輸出

SPECIALIST   CONTENTS UPDATE_COUNT 
Ram     Updates   23 
Har     Legis    6 
Ram     Updates   65 

我想輸出格式在下面的格式請幫助我。

  Har Ram Total 
Updates 0 88 88 
Legis 6 - 6 
Total 6 88 94 

感謝

+3

100%真正的問題。 gdoron

+0

你應該編輯你的問題來指定你已經試圖解決你的問題。 – Rcosta

+0

[Oracle SQL數據透視查詢]的可能重複(http://stackoverflow.com/questions/4841718/oracle-sql-pivot-query) – APC

回答

3

您沒有指定要使用甲骨文的版本。如果你在Oracle 11g中,那麼你可以使用PIVOT函數。如果不是,那麼您可以使用CASE語句的聚合函數。下面是如何產生的結果severl版本:

select contents, 
    sum(case when specialist = 'Har' then update_count else 0 end) Har, 
    sum(case when specialist = 'Ram' then update_count else 0 end) Ram, 
    sum(case when specialist in('Har', 'Ram') then update_count else 0 end) Total 
from yourtable 
group by contents 
union all 
select 'total', 
    sum(case when specialist = 'Har' then update_count else 0 end) Har, 
    sum(case when specialist = 'Ram' then update_count else 0 end) Ram, 
    sum(case when specialist in('Har', 'Ram') then update_count else 0 end) Total 
from yourtable 

SQL Fiddle with Demo

或者你可以使用GROUP BY ROLLUP

select 
    case when contents is null then 'Total' else contents end contents, 
    sum(case when specialist = 'Har' then update_count else 0 end) Har, 
    sum(case when specialist = 'Ram' then update_count else 0 end) Ram, 
    sum(case when specialist in('Har', 'Ram') then update_count else 0 end) Total 
from yourtable 
GROUP BY rollup(contents); 

SQL Fiddle with Demo

或者你可以使用PIVOTROLLUP

select 
    case when contents is null then 'Total' else contents end contents, 
    sum(coalesce(Har, 0)) Har, 
    sum(coalesce(Ram, 0)) Ram, 
    sum(coalesce(Har, 0) + coalesce(Ram, 0)) Total 
from 
(
    select specialist, contents, update_count 
    from yourtable 
) src 
pivot 
(
    sum(update_count) 
    for specialist in ('Har' as Har, 'Ram' as Ram) 
) piv 
group by rollup(contents) 

SQL Fiddle with Demo