Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

oracle11g - Pivot in Oracle 11g

I have searched Stackoverflow about pivot in Oracle 11g but could not find the syntax that works for my situation.

Below is my query (runs in Oracle 11g).

select
age,
gender,
sum(hours) as hours
from table1
group by age, gender

Here is the O/P result

age gender   hours
25  Male     10
55  Female   5
45  Female   12

...And here is my desired O/P result

Age  Male   Female
25   10     0
45    0     12
55    0     5

...And here is my query

select *
from    
(
select
age,
gender,
sum(hours) as hours
from table1
)
pivot (
sum (hours) for gender in (
Male   as 'Male',
Female as 'Female')
)

...And here is the error:

ORA-00931: missing identifier

Could anyone please educate me please?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You were close:

select age, nvl(male, 0) male, nvl(female, 0) female
from    
(
  select age,  gender,  sum(hours) as hours
  from table1
  group by age, gender
)
pivot
(
  sum(hours) for gender in ('Male' as male, 'Female' as female)
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...