列出连接多个表时的总计和条件计数

时间:2015-01-26 00:31:26

标签: sql oracle

我已经获得了以下表格:

Hotel (hotelNo, hotelName,hotelAddress)   
Room (roomNo,hotelNo, type, price)
Guest (guestNo, guestName, guestAddress)
Booking (hotelNo,guestNo,dateFrom, dateTo, roomNo)

问题是:"仍在建设中的酒店比例是多少?列出酒店总数,酒店数量 完工,在建酒店数量和在建酒店的比例。"

对于我知道的酒店总数,我可以这样做:

SELECT COUNT(Hotel.hotelNo)
FROM HOTEL;

2家酒店正在建设中,我知道我可以查看使用:

SELECT COUNT(Hotel.hotelNo)
FROM HOTEL
INNER JOIN ROOM
ON ROOM.hotelNo = Hotel.hotelNo
HAVING COUNT(roomNo) = 0;

然后完成的酒店:

SELECT COUNT(Hotel.hotelNo)
FROM HOTEL
INNER JOIN ROOM
ON ROOM.hotelNo = Hotel.hotelNo
HAVING COUNT(roomNo) > 0;

我不知道如何将所有这些放入一个查询中。我试过这样的事情:

SELECT COUNT(Hotel.hotelNo),
(SELECT COUNT(Hotel.hotelNo)
FROM HOTEL
LEFT JOIN ROOM
ON ROOM.hotelNo = Hotel.hotelNo
GROUP BY Room.roomNo
HAVING COUNT(roomNo) = 0) as count
FROM HOTEL;

这要求尽管我有Hotel.hotelNo的分组声明,但添加时只给我一张10 {1}}的表格,因为有10家酒店,然后是10 2&# 39;因为有2家酒店正在建设中。

我希望它看起来像这样:

COUNT(Hotel.hotelNo)

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

SELECT tmp.*
     , (tmp.total-tmp.complete) AS construction
     , ((1-tmp.complete/tmp.total)*100) AS percentage
FROM ( SELECT COUNT(DISTINCT h.hotelNo) AS total
            , COUNT(DISTINCT r.hotelNo) AS complete
       FROM HOTEL h 
       LEFT JOIN ROOM r ON r.hotelNo = h.hotelNo ) tmp

SQLFiddle

答案 1 :(得分:0)

如果您要查询正在建设中的酒店,我会感到惊讶,

SELECT COUNT(Hotel.hotelNo)
FROM HOTEL
INNER JOIN ROOM
ON ROOM.hotelNo = Hotel.hotelNo
HAVING COUNT(roomNo) = 0;

实际上有效。我之所以这样说是因为它看起来像是一个左连接的查询,正在查找hotelNo中没有相应行的ROOM值。

以下是将两个查询放在一起的方法:

SELECT COUNT(*) AS total
     , SUM(DECODE(room_cnt, 0, 0, 1)) AS completed
     , SUM(DECODE(room_cnt, 0, 1, 0)) AS construction
     , SUM(DECODE(room_cnt, 0, 1, 0))/COUNT(*) AS percentage
  FROM (
    SELECT h.hotelNo, COUNT(r.roomNo) AS room_cnt
      FROM hotel h LEFT JOIN room r
     WHERE h.hotelNo = r.hotelNo
     GROUP BY h.hotelNo
);

如果您喜欢ANSI SQL,则可以使用CASE代替DECODE()