我有两张桌子
表1:ppl
Cust No.| sex
--------| -------
10 | M
13 | F
12 | M
19 | F
20 | M
22 | M
34 | F
表2:hobbies
Cust No. | Hobby
---------| ---------
10 | Movies
10 | Hiking
10 | Programming
12 | Biking
12 | Movies
12 | Reading
19 | Biking
20 | Reading
22 | Movies
34 | Flying
22 | Biking
我正试图从表格中以DESC
的顺序找到按男/女分布最受欢迎的爱好。
我已经编写了查询以找到DESC
订单
select Hobby, count(*)
from hobbies
group by Hobby
问题
如何将此与ppl
表格相关联,然后通过M / F为每个表格进行分配?
请注意,我希望最受欢迎的爱好是DESC顺序。首先,我需要最受欢迎的爱好,然后将其分解为M / F
基于上述设置的结果将是:
Hobby | M | F
-------------| -----|----
Movies | 3 | 0
Hiking | 1 | 0
Programing | 1 | 0
Biking | 2 | 1
Reading | 2 | 0
Flying | 0 | 1
答案 0 :(得分:4)
这是一个带有join
的条件聚合查询:
select h.Hobby,
sum(case when gender = 'F' then 1 else 0 end) as females,
sum(case when gender = 'M' then 1 else 0 end) as males
from hobbies h join
people p
on h.custno = p.custno
group by h.Hobby
order by count(*) desc;