Group By query - any other way?
I have the following table that contains the following data:
http://img513.imageshack.us/img513/9039/mycities.png
The CREATE statement and the inserts are at http://snipt.org/xoKl .
The table is a list of cities and each city belongs to a region and a country and each city has a founding date. The goal here is to get for each "Country / Region" pair a list of the oldest cities. We need the oldest city on the east coast of Canada, the oldest city on the west coast of the U.S and so on ...
The query that I use right now is:
SELECT * FROM MyCities
INNER JOIN
(SELECT Country, Region, MIN(FoundingDate) AS C开发者_JAVA百科ityFoundingDate
FROM MyCities
GROUP BY Country, Region ) AS subquery
ON subquery.CityFoundingDate = MyCities.FoundingDate
AND MyCities.Country = subquery.Country
AND MyCities.Region = subquery.Region
I just want to know whether there are other ways to write this group by query or not. :-)
Is this query efficient or not? Looking forward to a discussion.What about?
select country, region, city from MyCities mc1
where foundingDate <= ALL (
select foundingDate from MyCities as mc2
where mc1.country = mc2.country and mc1.region = mc2.region
)
How about something like this? Should work in Oracle (although I can't test it right now)
SELECT country, region, city, foundingdate
FROM (
SELECT country, region, city, foundingdate, MIN(founding_date) OVER PARTITION BY (country, region) min_date
FROM mycities) WHERE foundingdate=min_date
But what if there are two cities founded on the same year in the same country/region?
精彩评论