SQL查询 - 选择不同的ID与2个额外的列
林在SQL查询这样的工作:(由台访问的排序)SQL查询 - 选择不同的ID与2个额外的列
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
任何人都可以举手?期待您的光临!
假设你发现了一些对站定义顺序,这样就可以识别出“最后”和“第一”的一个,下面应该工作:
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。
+1,用于解释良好,格式良好的查询,解决应该提问的问题 – bernie 2012-03-28 16:45:11
它不仅适用于Oracle吗?他没有提到具体的DBMS。 – 2012-03-28 16:46:18
@AlexGitelman:应该与PostgreSQL,Oracle,DB2,SQL Server,Teradata,Sybase,Firebird 3.0一起工作。 CTE('WITH ...')不是绝对必要的,如果用派生表代替它,它也应该和H2和Derby一起工作(尽管有点丑陋) – 2012-03-28 16:47:52
数据库表没有任何可以基于此类查询的顺序。您需要额外的订单栏。 – bernie 2012-03-28 16:33:22
您使用SQLServer吗? – PraveenVenu 2012-03-28 16:34:02
是FirstStation = Denver for train 222有意或错字(正在等待伦敦) – Mikeb 2012-03-28 16:37:32