您没有指定您使用的 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