-8

I have a sql table in oracle as below and its name is scope.

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

and i want the output to be formatted in the below format please help me.

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

thanks

4

1 回答 1

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

或者您可以使用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

或者您可以PIVOT使用ROLLUP

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

于 2012-11-12T16:11:42.430 回答