SQL中的嵌套查询使用group by查找min和max

时间:2016-11-01 11:54:17

标签: mysql sql

我正试图解决的问题:

找到地址地区 名称,以便区域内的最小邮政编码在所有地区都是最大的。确保您的查询忽略空的邮政编码和地区名称。

我可以轻松找到最低邮政编码。我在编写嵌套查询时遇到问题,然后从这些结果中找到最大邮政编码。

到目前为止,我已经使用过:

SELECT min(postal_code), district 
FROM address 
WHERE district != '' AND postal_code != '' 
GROUP BY district;

1 个答案:

答案 0 :(得分:0)

你驾驶室要么使用这个

Select Rank() Over (Partition by district Order by postal_code DESC ) AS 

Rank,district, postal_code  from address district != '' AND postal_code != '' 

或者你可以这个

 Select Rank() Over (Partition by district Order by postal_code DESC ) AS 

Rank,district, postal_code into #Temp  from address district != '' AND postal_code != '' 

现在使用

Select district, postal_code from #Temp