如何连接 2 SQL 列和行不相等的查询

How to Connect 2 SQL queries with unequal column and rows

我想加入这两个查询并显示如下图所示的结果。我该怎么做。我是一名使用 Oracle-Apex 的学生。

查询 #1:

SELECT 
    Room_Dim.BandDesc, TO_CHAR(BookedStartDate, 'Month') AS Month,     
    COUNT(Fact_Bookings_Payments.RoomID) AS Reserved 
FROM 
    Room_Dim, Fact_Bookings_Payments
WHERE 
    Room_Dim.RoomID = Fact_Bookings_Payments.RoomID 
GROUP BY 
    Room_Dim.BandDesc, TO_CHAR(BookedStartDate, 'Month')
ORDER BY 
    Room_Dim.BandDesc, TO_CHAR(BookedStartDate, 'Month') DESC;

查询#2:

SELECT 
    Room_Dim.BandDesc, COUNT(Room_Dim.RoomID) AS TotalRooms
FROM 
    Room_Dim
GROUP BY 
    Room_Dim.BandDesc
ORDER BY 
    Room_Dim.BandDesc;

[在此处输入图片描述]

您可以使用 join 来获得您想要的结果。如果仅当两个查询中都存在 BandDesc 时才想 select 行,那么内部联接就可以了。

select t.BandDesc,Month, Reserved, TotalRooms from

(SELECT Room_Dim.BandDesc, to_char(BookedStartDate, 'Month') AS Month,     COUNT(Fact_Bookings_Payments.RoomID)AS Reserved 
FROM Room_Dim, Fact_Bookings_Payments
WHERE Room_Dim.RoomID = Fact_Bookings_Payments.RoomID 
GROUP BY Room_Dim.BandDesc, to_char(BookedStartDate, 'Month'))t

inner join 

(SELECT Room_Dim.BandDesc, COUNT(Room_Dim.RoomID) AS TotalRooms
FROM Room_Dim
GROUP BY Room_Dim.BandDesc)t2

on t.BandDesc=t2.BandDesc       
ORDER BY BandDesc, Month DESC

如果你想连接三个表,那就是这样的:

select ... from t
inner join t2     on t.BandDesc=t2.BandDesc       
inner join t3     on t.BandDesc=t3.BandDesc       
ORDER BY BandDesc, Month DESC

我建议将查询表述为:

SELECT r.BandDesc, trunc(bp.BookedStartDate, 'Month') AS Month,     
       COUNT(bp.RoomID) AS Reserved,
       r.total_rooms
FROM (SELECT r.*,
             COUNT(*) OVER (PARTITION BY r.BandDesc) as total_rooms
      FROM Room_Dim r
     ) r LEFT JOIN
     Fact_Bookings_Payments bp
     ON r.RoomID = pb.RoomID 
GROUP BY r.BandDesc, trunc(bp.BookedStartDate, 'Month'), rd.total_rooms
ORDER BY r.BandDesc, trunc(bp.BookedStartDate, 'Month') DESC;

备注:

  • 从不FROM 子句中使用逗号。 始终使用正确、明确、标准、可读的JOIN语法。
  • LEFT JOIN 确保结果中包含没有保留的波段。
  • 我用 trunc() 替换了 to_char()。主要区别在于 trunc() 包括年份 - 如果您查看月份,您确实应该包括年份,除非您非常有意地想在不同年份计算同一个月。
  • COUNT(*) OVER 计算相同频段的房间。