SQL: Query for flights table

Sherlan Emmanuel Burgonia 86 Reputation points
2022-09-30T05:59:21.343+00:00

Hi everyone,

I have a flights table and I need help on identifying whether the ticket number is one-way or round trip as seen in the image.

Here are the specifications I need to satisfy:

  1. If there is only one coupon for a ticket, it's automatically considered one-way.
  2. If the next origin is equivalent to current destination AND the current origin is the same as the next destination, this should be "roundtrip". Given that they have the same ticket number and the coupon >= 1.

I am actually having a JOIN statement from the two table but I do not know where to contain the previous/next destinations.

246372-image.png

Can you help me with this?

Azure SQL Database
Azure Database for MySQL
Azure Database for MySQL
An Azure managed MySQL database service for app development and deployment.
992 questions
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2022-09-30T08:05:53.68+00:00

    Check a query:

    select *,  
        case when   
            ( Origin = lag(Destination) over (partition by TicketNumber order by Coupon) and   
              Destination = lag(Origin) over (partition by TicketNumber order by Coupon))  
            or  
            ( Origin = lead(Destination) over (partition by TicketNumber order by Coupon) and  
              Destination = lead(Origin) over (partition by TicketNumber order by Coupon))  
        then 'Roundtrip'  
        else 'One-way' end as [Value]  
    from Flights  
    order by TicketNumber, Coupon  
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Sherlan Emmanuel Burgonia 86 Reputation points
    2022-10-03T05:50:33.657+00:00

    Hi @Viorel this works thank you

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.