2012-07-14 90 views
0

的最大值派生列所以我有這個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 Appleton 8 
Texas  Richmond 5 
Texas  Dupree  7 
Texas  Brighton 10 

我需要確定哪些是最人口稠密縣每個州。

select state, county, max(population) from state_pops group by state order by state; 

產生

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 

所以我需要以某種方式獲得一列,可能是某種形式的CASE..WHEN的有任何想法嗎?

TIA,

仍然甜菊學習

+0

使用功能我explaiend的方式嘗試 – Abadis 2012-07-14 06:42:54

回答

2

您可以使用此解決方案:

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 

看到一個SQL-Fiddle Demo

0

使用此

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;;