If I have a table containing gas stations specifying the city, the name and the latitude+longitude of each gas station:
city | name | latitude | longitude
---------------------------------------------------------
Berlin | GasPump1 | 52.5 | 13.5
Berlin | GasPump2 | 52.52 | 13.51
Zagreb | INA1 | 45.8 | 16
Zagreb | INA2 | 45.81 | 16.01
Zagreb | INA3 | 45.82 | 15.99
how would I go about obtaining a single representative entity for each city, using a single SQL query? That is, how would I go about implementing the following pseudocode using a single query:
representativeStationsArray = []
citiesArray = sqlQuery("SELECT DISTINCT city FROM gasstations")
for city in citiesArray:
representativeStation = sqlQuery(
"SELECT * FROM gasstations WHERE city = ? LIMIT 1;",
city)
representativeStationsArray.append(representativeStation)
I’ve accepted an answer, but I thought it might be interesting to explain my needs for future readers.
On iOS, once the user zooms out, too many annotations being displayed on the map view slows the app down. First experimental solution that I’m trying out (and which should be ok for the country I’m developing this for) is to filter the annotations by city, and just display a random annotation for each city.
If this proves unsatisfactory, I’ll look for another solution.
If by “representative row” you just mean “any arbitrary row where the city matches” then you can just use a GROUP BY:
The fields other than
citywill be populated with data from an arbitrary group-matching row.From the docs at http://sqlite.org/lang_select.html#resultset (emphasis mine):
Note: It works this way for SQLite and for MySQL, and a few other databases. But many (most?) databases do not allow you to select non-aggregate fields in a grouped query. So just be mindful of this if you ever switch databases or deploy to a different production database.