以表格格式输出

时间:2012-11-12 16:01:06

标签: sql oracle pivot

我在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

感谢

1 个答案:

答案 0 :(得分:3)

您没有指定您使用的是哪个版本的Oracle。如果您使用的是Oracle 11g,则可以使用PIVOT功能。如果没有,那么您可以使用带有CASE语句的聚合函数。以下是如何生成结果的版本:

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