Reputation: 5299
I have tables like this.
I would like to groupby
and aggregate this in diffrent aggregate functions.
product sex age
A M 10
B F 20
A F 30
C M 40
my desired result is like below.
Now I can group in product
key, but in this case, I must group them byproduct
andsex
.
Are there any way to achieve it?
count(M) count(F) avarage(M) average(F)
A 1 1 10 30
B 0 1 NA 20
C 1 0 40 NA
Thanks
Upvotes: 0
Views: 60
Reputation: 35910
You can simply use the PIVOT
as follows:
select * from your_Table
pivot
(count(1) as cnt, avg(age) as average for sex in ('M','F'))
Upvotes: 0
Reputation: 164099
With conditional aggregation:
select product,
sum(case when sex = 'M' then 1 else 0 end),
sum(case when sex = 'F' then 1 else 0 end),
avg(case when sex = 'M' then age end),
avg(case when sex = 'F' then age end)
from tablename
group by product
Upvotes: 1