繁体   English   中英

SQL Pivot 在 varchar 列上

[英]SQL Pivot on varchar columns

我有一个看起来像这样的结果集:

FlightCode  col2    Col3    SourceAirportCode
Flight007   NYC     SOURCE      64
Flight008   ORD     TARGET      87
Flight007   SEA     TARGET      NULL
Flight008   PHX     SOURCE      NULL

我试图达到的最终结果是:

FlightCode  Source  Target  SourceAirportCode
Flight007   NYC     SEA     64
Fight008    PHX     ORD     87

这是 pivot 问题吗? 我尝试了一些旋转但没有运气,或者我只是对 Pivot 了解不够。这是

SQL 小提琴演示

使用架构和插入语句。 请指教。

假设航班代码实际匹配,则使用条件聚合:

select flightcode,
       max(case when col3 = 'SOURCE' then col2 end) as source,
       max(case when col3 = 'TARGET' then col2 end) as target,
       max(SourceAirportCode) as SourceAirportCode
from t
group by flightcode;

您可以使用自联接并将一个表视为源,将另一个表视为目标。

WITH flight(FlightCode,  col2,    Col3,    SourceAirportCode)
AS 
(
 SELECT 'Flight007','NYC','SOURCE',64   UNION
 SELECT 'Flight008','ORD','TARGET',87   UNION
 SELECT 'Flight007','SEA','TARGET',NULL UNION
 SELECT 'Flight008','PHX','SOURCE',NULL
)

SELECT f.FlightCode, s.col2 as 'SOURCE', t.col2 as 'TARGET',
       f.SourceAirportCode
FROM flight f
JOIN flight s ON s.Col3 = 'SOURCE' AND s.FlightCode = f.FlightCode
JOIN flight t ON t.Col3 = 'TARGET' AND t.FlightCode = f.FlightCode
WHERE f.SourceAirportCode IS NOT NULL


FlightCode  SOURCE  TARGET  SourceAirportCode
 Flight007  NYC      SEA    64
 Flight008  PHX      ORD    87

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM