Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在mysql中选择每个组中的第一行_Mysql_Sql - Fatal编程技术网

在mysql中选择每个组中的第一行

在mysql中选择每个组中的第一行,mysql,sql,Mysql,Sql,我有一个表,有两列-区域和专业 region | profession India | IT India | IT US | HR US | HR India | HR 我想展示每个地区最受欢迎的职业。输出应仅为 Region | Profession India | IT US | HR 首先,获得每组结果的计数。然后您需要为每个组建立一个订单——mysql可以使用用户定义的变量来实现这一点 下面是一个例子: select

我有一个表,有两列-区域和专业

region   |  profession
India    |  IT
India    |  IT
US       |  HR
US       |  HR
India    |  HR
我想展示每个地区最受欢迎的职业。输出应仅为

Region | Profession
India  | IT
US     | HR

首先,获得每组结果的
计数。然后您需要为每个组建立一个订单——mysql可以使用
用户定义的变量来实现这一点

下面是一个例子:

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

我曾想过按区域对表格进行分组,然后对每组的不同职业进行计数,但这似乎不起作用。请添加示例查询和结果,以便我们可以从您似乎知道的内容中解决您需要知道的内容。现在,您正在向tout court寻求解决方案。感谢您的帮助!