sql—如何基于此特定场景从主表中提取数据?

eh57zj3b  于 2021-08-13  发布在  Java
关注(0)|答案(2)|浏览(199)

我正在使用 SQL Server 2014 . 我有一个表(t1),其中包含取消预订及其等效重新预订的ID列表。
表格摘录 T1 :

CancelledID       Re-bookingID
  301                754
  387                801
  400                900
  ...

每个cancelleId在re bookingid列中都有一个唯一的等价项。
我还有一张table( T2 )其中包含所有BookingID的列表以及与每个id相关的附加信息。此表的摘录如下所示:

BookingID     MonthOfStay      RoomNights
...
301             2019-03-01        10
387             2019-04-01         7
400             2019-03-01         5
754             2019-08-01        10
801             2019-09-01         3
900             2019-07-01         5
900             2019-08-01         4
...

我需要一个t-sql查询,它将为我提供以下输出:

BookingID       Cancelled_MonthOfStay     Re-booking_MonthOfStay     RoomNights
    301                2019-03-01                                           10
    387                2019-04-01                                            7
    400                2019-03-01                                            5
    754                                           2019-08-01                10
    801                                           2019-09-01                 3
    900                                           2019-07-01                 5
    900                                           2019-08-01                 4

如您所见,重新预订房间的时间可以超过2个月,并增加房间住宿。
我在考虑两个表之间的“连接”,但是我被用于“连接”的逻辑卡住了(如果这是解决问题的正确方法的话)。
注意:最后要考虑的是使用此数据构建一个矩阵,其中取消的\u monthofstay作为行,重新预订的\u monthofstay作为列。此矩阵中的值将是总的roomnights。
任何帮助都将不胜感激。

fafcakar

fafcakar1#

似乎最简单的方法是在 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;
jmp7cifd

jmp7cifd2#

可以将t1表左键联接到t2表两次。然后使用case将右边的列留空。

SELECT T2.bookingID,
    case when canc.CancelledID is not null then t2.monthOfSTay end as cancelled_MonthOfStay,
    case when reb.rebookingID is not null then t2.monthOfStay end as rebooking_MonthOfStay

FROM T2
LEFT JOIN T1 as canc
    on T2.bookingID = canc.CancelledID
LEFT JOIN T1 as reb
    on T2.bookingID = reb.rebookingID

相关问题