2012-11-12 111 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