-8

以下のように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

ありがとう

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 に答える