SQL查询 - 使用2个额外列选择不同的ID

时间:2012-03-28 16:31:30

标签: sql

我在这样的SQL查询中工作:(按电台访问排序)

TRAIN_ID   TYPE   STATION
111        'KC'   New York
111        'KC'   Washington
111        'KC'   Boston
111        'KC'   Denver
222        'FC'   London
222        'FC'   Paris

我想选择不同的列车,实际的行必须包括第一站和最后一站:

TRAIN_ID    TYPE     FIRSTSTATION    LASTSTATION
111         'KC'     New York        Denver
222         'FC'     Denver          Paris

任何人都可以伸出援助之手?谢谢你期待!

1 个答案:

答案 0 :(得分:3)

假设您找到了在工作站上定义订单的内容,以便您可以识别“最后”和“第一个”,则以下内容应该有效:

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

这假定some_order_column可用于识别最后一站和第一站。

它还假设type对于train_id和station的所有组合始终相同。

显示的语法是标准ANSI SQL,应该适用于大多数现代DBMS。