Im working in an SQL Query like this: (sorted by the station visits)
TRAIN_ID TYPE STATION
111 'KC' New York
111 'KC' Washington
111 'KC' Boston
111 'KC' Denver
222 'FC' London
222 'FC' Paris
I’d like to SELECT distinct trains, and actual row must include the first and the last station like:
TRAIN_ID TYPE FIRSTSTATION LASTSTATION
111 'KC' New York Denver
222 'FC' Denver Paris
Anyone can give a hand? Thank you in anticipation!
Assuming you find something to define an order on the stations so that you can identify the “last” and “first” one, the following should work:
This assumes that
some_order_columncan be used to identify the last and first station.It also assumes that the
typeis always the same for all combinations of train_id and station.The shown syntax is standard ANSI SQL and should work on most modern DBMS.