Opi
Opi

Reputation: 3

SQL Query - SELECT distinct IDs with 2 extra column

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!

Upvotes: 0

Views: 178

Answers (1)

user330315
user330315

Reputation:

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:

WITH numbered_stations AS (
  SELECT train_id, 
         type, 
         row_number() over (partition by train_id order by some_order_column) as rn,
         count(*) over (partition by train_id) as total_stations
  FROM the_unknown_table
)
SELECT f.train_id,  
      f.type, 
      f.station as first_station, 
      l.station as last_station
FROM (SELECT train_id, 
         type
         station
  FROM numbered_stations
  WHERE rn = 1
) f
  JOIN (SELECT train_id, 
               type, 
              station
        FROM numbered_stations 
        WHERE rn = total_stations) l 
  ON f.train_id = l.train_id
ORDER BY train_id

This assumes that some_order_column can be used to identify the last and first station.

It also assumes that the type is 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.

Upvotes: 3

Related Questions