I'm querying bus stops from a database, and I wish to have it only return 1 stop per bus line/direction. This query does just that:
Stop.select("DISTINCT line_id, direction")
Except that it won't give me any other attribute than those 2. I tried a couple of other queries to have it return the id in addition to the line_id and direction fields (ideally it would return all columns), with no luck:
Stop.select("DISTINCT line_id, direction, id")
and
Stop.select("DISTINCT(line_id || '-' || direction), id")
In both cases, the query loses its distinct clause and all rows are returned.
Some awesome dude helped me out and suggested to use a subquery to have it return all the ids:
Stop.find_by_sql("SELECT DISTINCT a1.line_id, a1.direction, (SELECT a2.id from stops a2 where a2.line_id = a1.line_id AND a2.direction = a1.direction ORDER BY a2.id ASC LIMIT 1) as id FROM stops a1
I can then extract all the ids and perform a 2nd query to fetch the full attributes for each stop.
Is there a way to have it all inside 1 query AND have it return all the attributes?