我有一个包含两列的表 - 区域和专业
region | profession
India | IT
India | IT
US | HR
US | HR
India | HR
我希望在每个地区展示最受欢迎的专业。输出应该只是
Region | Profession
India | IT
US | HR
答案 0 :(得分:0)
首先,获得每组count
的结果。然后你需要为每个组建立一个订单 - mysql可以使用user-defined variables
执行此操作。
以下是一个例子:
select region, profession
from (
select region, profession,
@rn:=if(@oldregion=region,@rn+1,0) rn,
@oldregion:=region
from (
select region, profession, count(*) cnt
from yourtable
group by region, profession) t, (select @rn:=0, @oldregion='') t2
order by region, cnt desc) t3
where rn = 0
这是使用相关子查询的另一种解决方案:
select distinct region, (
select profession
from yourtable t2
where t.region = t2.region
group by region, profession
order by count(*) desc
limit 1) as profession
from yourtable t