MS SQL:
表一:路线 - 表二:停止(使用int字段[seq]获取停靠顺序,关键字段ID)
如何将[routes]加入[stops]表并仅将第一个和最后一个路由返回到一行?
假设我做了一个简单的连接:
Route 1 | Stop 1
Route 1 | Stop 2
Route 1 | Stop 3
Route 2 | Stop 1
Route 2 | Stop 2
我希望它返回:
Route 1 | Stop 1 | Stop 3
Route 2 | Stop 1 | Stop 2
我可以加入他们并获得Min(Seq)和Max(Seq),但不知道如何获得ID而不是Seq。这几乎就像我想做两个连接,但是多个字段。我需要它才能有效,因为在给定时间返回了数千条路线。所以我不认为一个表值得函数来获得止损将是有益的。但是,如果我可以获得最小和最大seq,返回相关的停止ID,我可以简单地将Stops加入这些以获取相关数据。
答案 0 :(得分:4)
;WITH S
AS (SELECT *,
ROW_NUMBER() OVER (PARTITION BY RouteId ORDER BY seq) AS RN1,
ROW_NUMBER() OVER (PARTITION BY RouteId ORDER BY seq DESC) AS RN2
FROM Stops)
SELECT R.Route,
S1.Stop,
S2.Stop
FROM Routes R
JOIN S S1
ON R.Id = S1.RouteId
JOIN S S2
ON R.Id = S2.RouteId
WHERE S1.RN1 = 1
AND S2.RN2 = 1