根据SQL Server中的单个列查找源/目标

时间:2017-12-21 10:26:00

标签: sql sql-server

我有一个带有以下数据的SQL Server表

ID  Source     Destination  PFID
1   Loc X      Loc Y        1
2   Loc Y      Loc Z        1
3   Delhi      Kolkata      3
4   Kolkata    Dhaka        3

上表列出了不同城市之间转机航班的数据。我想要一个以下格式的结果 -

Source     Destination  PFID
Loc X      Loc Z        1
Delhi      Dhanka       3

请告知如何实现这一目标。

2 个答案:

答案 0 :(得分:2)

尝试以下

SELECT q.PFID,p1.Source,p2.Destination
FROM
  (
    SELECT PFID,MIN(ID) SourceID,MAX(ID) DestinationID
    FROM [Your Table]
    GROUP BY PFID
  ) q
JOIN [Your Table] p1 ON p1.ID=q.SourceID
JOIN [Your Table] p2 ON p2.ID=q.DestinationID

如果您的SQLServer版本支持它们,您可以使用窗口函数FIRST_VALUELAST_VALUE

SELECT DISTINCT
  PFID,
  FIRST_VALUE(Source)OVER(PARTITION BY PFID ORDER BY ID ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) Source,
  LAST_VALUE(Destination)OVER(PARTITION BY PFID ORDER BY ID ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) Destination
FROM [Your Table]

如果ID不一致,那么您可以使用递归CTE

;WITH cte AS(
  -- start point
  SELECT ID,Source,Destination,PFID,1 step
  FROM [Your Table]
  WHERE PFID=ID

  UNION ALL

  -- next point
  SELECT t.ID,c.Source,t.Destination,t.PFID,c.step+1
  FROM [Your Table] t
  JOIN cte c ON t.Source=c.Destination
)
SELECT PFID,Source,Destination
FROM 
  (
    SELECT
      PFID,
      Source,
      Destination,
      step,
      MAX(step)OVER(PARTITION BY PFID) LastStep
    FROM cte
  ) q
WHERE step=LastStep

这是两个提供Yogesh Sharma和我的第一个查询的查询的共生

SELECT s.PFID,s.Source,d.Destination
FROM
  (
    SELECT PFID,MIN(CASE WHEN PFID=ID THEN Source END) Source,MAX(ID) DestinationID
    FROM [Your Table]
    GROUP BY PFID
  ) s
JOIN [Your Table] d ON d.ID=s.DestinationID

答案 1 :(得分:2)

只需使用条件聚合的group by子句

select min(case when pfid = id then Source end) [Source], 
       max(case when pfid <> id then Destination end) [Destination], PFID 
from table
group by PFID

修改:

您还可以使用first_value()last_value()功能直接获取源和目标站

select distinct first_value(Source) over (partition by PFID order by PFID) , last_value(Destination) over (partition by PFID order by PFID), PFID 
from table
order by PFID

注意:以上内容是根据Q

中提供的数据进行测试的