sql透视

6rvt4ljy  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(353)

我的结果集如下所示:

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

这是轴心问题吗?我试过旋转,但运气不好,或者我对旋转的了解不够。这里是
sql fiddle演示
使用schema和insert语句。请告知。

4c8rllxm

4c8rllxm1#

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

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;
z9ju0rcb

z9ju0rcb2#

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

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

相关问题