There are some constraints to this question; I don't have the ability to fundamentally alter any database structure.
The challenge here is that I have rows in a database that contain information that really should be on its own row. A somewhat simplified example of the column structure:
[PersonID] [FirstName] [LastName] [FirstNameGuest1] [LastNameGuest1]
1 Ringo Starr John Lennon
2 George Harrison Paul McCartney
I need to split these out like this in order to be able to run the reports I need:
[PersonID] [FirstName] [LastName]
1 Ringo Starr
1 John Lennon
2 George Harrison
2 Paul McCartney
Since I'm using this to produce a view, I've had to just reference the same table for each group of guest columns and use UNION ALLs
to tie them all together.
However, since then I've had to build queries of ever-increasing complexity on top of the derived view. Each layer of complexity causes the results to return more and more slowly.
Am I taking a fundamentally bad approach? Are there other, more correct ways to model the data in the way that I need?
Here's part of the actual query so you can see what I'm dealing with:
--Primary Record
SELECT
'Franchisee' AS 'Type',
Confirmation AS 'BelongingTo',
0 AS 'GuestNo',
FirstName,
LastName,
FF_27557_152972 AS 'HotelChoice',
HotelCheckIn,
HotelCheckOut,
HotelSmoking AS 'Smoking',
(CASE FF_27554_1 WHEN 'Yes' THEN 1 ELSE 0 END) AS 'PrimaryRoomHolder',
'' AS 'SharingWith',
'None' AS 'SharingWithName'
FROM dbo.[Table]
WHERE Type = 'Production' AND Submitted = 1 AND Cancelled = 0 AND Label = 'Primary'
UNION ALL
-- First Guest
SELECT
'Guest' AS 'Type',
Confirmation AS 'BelongingTo',
1 AS 'GuestNo',
FF_27637_1 AS 'FirstName',
FF_27637_152806 AS 'LastName',
FF_27637_152822 AS 'HotelChoice',
FF_27637_152813 AS 'HotelCheckIn',
FF_27637_152821 AS 'HotelCheckOut',
FF_27637_152824 AS 'Smoking',
(CASE WHEN FF_27637_152822 IS NOT NULL THEN 1 ELSE 0 END) AS 'PrimaryRoomHolder',
FF_27637_154245 AS 'SharingWith',
(CASE CAST(FF_27637_154245 AS integer)
WHEN 0 THEN FirstName + ' ' + LastName
WHEN 1 THEN FF_27637_1 + ' ' + FF_27637_152806
WHEN 2 THEN FF_27742_1 + ' ' + FF_27742_153577
WHEN 3 THEN FF_27638_1 + ' ' + FF_27638_152814
WHEN 4 THEN FF_27639_1 + ' ' + FF_27639_152817
WHEN 5 THEN FF_27640_1 + ' ' + FF_27640_152852
WHEN 6 THEN FF_27641_1 + ' ' + FF_27641_152860
WHEN 7 THEN FF_27642_1 + ' ' + FF_27642_152868
WHEN 8 THEN FF_27643_1 + ' ' + FF_27643_152877
WHEN 9 THEN FF_27644_1 + ' ' + FF_27644_152885
WHEN 10 THEN FF_27645_1 + ' ' + FF_27645_152893
ELSE 'None' END) AS 'SharingWithName'
FROM dbo.Event_213_1546 AS Event_213_1546_10
WHERE Type = 'Production' AND Submitted = 1 AND Cancelled = 0 AND Label = 'Primary' AND FF_27637_1 IS NOT NULL
.
.
.
(Iterates through 9 more guests exactly like "First Guest")