I’m working with airline data, so I have a query like this
SELECT Invoices.PNR, Segments.Depart, Segments.Arrival, Segments.DepartDateTime
FROM Invoices AS i INNER JOIN Segments AS s
ON i.Invoice_ID = s.Invoice_ID`
WHERE PNR = 'AAAAAA'
This returns
PNR Depart Arrival DepartDateTime
AAAAAA DFW MCI 7/2/2012 7:30 AM
AAAAAA MCI LAX 7/2/2012 11:30 AM
AAAAAA LAX DFW 7/4/2012 2:30 PM
I have a column in Invoices called routing that I want to show ‘DFW-MCI-LAX-DFW’ Is this possible using a SQL only method ? The segments are listed in order, so DFW-MCI is first then MCI-LAX then LAX-DFW.
EDIT: If I could update the database with DFW-MCI-MCI-LAX-LAX-DFW that is perfectly acceptable. I can strip out the duplicate entries on the view layer.
I can easily write this in ColdFusion, but the looping and thousands of database updates takes forever. I could also do a mass update for every 100 records, but I’d like to avoid using anything other than SQL altogether
Here’s how you can update the values, assuming this is a one-time update (if it’s not, you’re going to have to run this every time
Segmentshas any changes):Content of
Invoicesafter the update:If you are on SQL Server 2017 or greater, this is a lot easier with
STRING_AGG():