简体   繁体   English

SQL Pivot 在 varchar 列上

[英]SQL Pivot on varchar columns

I have a result set that looks like this:我有一个看起来像这样的结果集:

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

The end result I'm trying to achieve is this:我试图达到的最终结果是:

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

Is this a pivot problem?这是 pivot 问题吗? I tried some pivoting but no luck or I just do not know enough about Pivot. Here is我尝试了一些旋转但没有运气,或者我只是对 Pivot 了解不够。这是

SQL Fiddle Demo SQL 小提琴演示

with schema and insert statements.使用架构和插入语句。 Please advise.请指教。

Assuming the flight codes actually match, then use conditional aggregation:假设航班代码实际匹配,则使用条件聚合:

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;

You can use self join and consider one table as source and other table as Target.您可以使用自联接并将一个表视为源,将另一个表视为目标。

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