问题
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?
回答1:
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)
);
回答2:
The reason for 'missing identifier' error is - the expected syntax is
<Value> As <identifier>
So when you give - Male as 'Male' , it can not find the identifier after 'as' and hence gives this error.
Also even if you correct that error, the next error would come as "not a single-group group function" as you are selecting age and gender alongside aggregate function sum(hours) without grouping by (I just mentioned this as a technical point, you don't actually need any group by here).
Please refer to the below code for your output.
SELECT age,nvl(male,0) AS male,nvl(female,0) AS frmale FROM
(SELECT *
FROM (
SELECT age,gender,hours
FROM test_subha3)
pivot (sum(hours) FOR gender IN ('Male' AS Male,'Female' AS Female))
)
来源:https://stackoverflow.com/questions/23700034/pivot-in-oracle-11g