Mysql 基于子群最大值的派生列的实现
所以我有一个MySQL 5.0.24表Mysql 基于子群最大值的派生列的实现,mysql,Mysql,所以我有一个MySQL 5.0.24表 select state, county, population from state_pops order by state, county; 屈服 Arizona Yapavai 4 Arizona Pueblo 5 Arizona Pinal 8 Arizona Maricopa 13 Michigan Lawson 3 Michigan Maple 4 Michigan Apple
select state, county, population from state_pops order by state, county;
屈服
Arizona Yapavai 4
Arizona Pueblo 5
Arizona Pinal 8
Arizona Maricopa 13
Michigan Lawson 3
Michigan Maple 4
Michigan Appleton 8
Texas Richmond 5
Texas Dupree 7
Texas Brighton 10
Arizona Maricopa 13
Michigan Appleton 8
Texas Brighton 10
我需要确定每个州人口最稠密的县
select state, county, max( population) from state_pops group by state order by state;
屈服
Arizona Yapavai 4
Arizona Pueblo 5
Arizona Pinal 8
Arizona Maricopa 13
Michigan Lawson 3
Michigan Maple 4
Michigan Appleton 8
Texas Richmond 5
Texas Dupree 7
Texas Brighton 10
Arizona Maricopa 13
Michigan Appleton 8
Texas Brighton 10
简单。但现在我需要在每个州的人口最多的县
列出所有州的所有县,像这样
Arizona Yapavai 4 NO
Arizona Pueblo 5 NO
Arizona Pinal 8 NO
Arizona Maricopa 13 YES
Michigan Lawson 3 NO
Michigan Maple 4 NO
Michigan Appleton 8 YES
Texas Richmond 5 NO
Texas Dupree 7 NO
Texas Brighton 10 YES
所以我需要以某种方式导出一个专栏,也许是某种形式的案例……什么时候有什么想法
蒂亚
仍在学习Stev您可以使用此解决方案:
SELECT a.state,
a.county,
a.population,
COALESCE(b.isMostPop, 'NO') AS flag
FROM state_pops a
LEFT JOIN
(
SELECT state, MAX(population) AS maxpop, 'YES' AS isMostPop
FROM state_pops
GROUP BY state
) b ON a.state = b.state AND a.population = b.maxpop
请参见a使用此
select state, county, population,heaviest(state,conuty) from state_pops order by state, county;
对于该功能,请执行以下操作:
create function `heaviest`(`fstate` char(10),`fcounty` char(10))
RETURNS char(3)
BEGIN
declare ans char(3);
if (select population from yourtable where state=fstate and county=fcounty)>=(select max(population) from yourtable group by state having state=fstate and count=fcount) then set ans='yes';
else set ans='no';
end if;
return ans;
END;;
试着用我解释的方式使用函数