2016-03-22 43 views
1

我已經找到每個地區的最小後綴,現在想要找到所有這些地區郵政編碼最小值的最大值。我陷入瞭如何做最大值的同時保持其他部分不變。嵌套選擇查詢 - mysql sakila數據庫

select 
    district, 
    postal_code, 
    min(postal_code) from address 
group by district 
having district is not null and district !="" and postal_code>0 
order by district; 

result

+0

您正在選擇不在「GROUP BY」列表中的「postal_code」列。你應該解決這個問題。 –

回答

1

如果只需要max(min_postal_code),使用下面的語句。

select max(min_postal_code) 
from (
    select district, min(postal_code) AS min_postal_code 
    from address 
    where district is not null and district !="" and postal_code>0 
    group by district 
    order by district) t 

如果區域名稱與MAX(min_postal_code)也需要。使用以下語句。

select * 
from (select district, min(postal_code) AS min_postal_code 
    from address 
    where district is not null and district !="" and postal_code>0 
    group by district) t 
where t.min_postal_code = 
(
    select max(min_postal_code) 
    from (select district, min(postal_code) AS min_postal_code 
     from address 
     where district is not null and district !="" and postal_code>0 
     group by district) t2 
); 
+0

是的這有效!你可以在最後一行解釋t(剛開始使用MySql) – nkart1

+0

如果我還想選擇相應的分區名稱,該怎麼辦? 我嘗試這樣做: 選擇區,MAX(min_postal_code) 從( 選擇區,分(POSTAL_CODE)從地址 min_postal_code 其中區不爲空,區= 「」 和POSTAL_CODE> 0 組由區 !按地區排列)t; 但我得到的地區名稱是錯誤的(最大值是正確的,雖然 – nkart1

+0

更新了帖子,再試一次。 –