Похоже, самый простой способ - это развернуть данные в таблице «Cancellations
», а затем использовать выражение CASE
для отображения данных в соответствующем столбце:
USE Sandbox;
GO
CREATE TABLE dbo.Cancellations (CancelledID int, RebookingID int)
INSERT INTO dbo.Cancellations
VALUES (301,754),
(387,801),
(400,900);
GO
CREATE TABLE dbo.Bookings (BookingID int, MonthOfStay date, RoomNights int)
INSERT INTO dbo.Bookings
VALUES (301,'20190301',10),
(387,'20190401', 7),
(400,'20190301', 5),
(754,'20190801',10),
(801,'20190901', 3),
(900,'20190701', 5),
(900,'20190801', 4);
GO
SELECT B.BookingID,
CASE V.BookingType WHEN 'Cancellation' THEN B.MonthOfStay END AS CancelledMonthOfStay,
CASE V.BookingType WHEN 'Rebooking' THEN B.MonthOfStay END AS RebookedMonthOfStay,
B.RoomNights
FROM dbo.Cancellations C
CROSS APPLY (VALUES(C.CancelledID, 'Cancellation'),(C.RebookingID, 'Rebooking')) V(BookingID,BookingType)
JOIN dbo.Bookings B ON V.BookingID = B.BookingID
ORDER BY B.BookingID;
GO
DROP TABLE dbo.Cancellations;
DROP TABLE dbo.Bookings;