2013-03-20 170 views
0

我正在嘗試查詢酒店數據庫以查找預訂的總費用。我正在使用子選擇查詢,但我不斷收到錯誤。SQL子選擇查詢

這是查詢,我希望它顯示預訂ID和房間號以及總成本。

SELECT BOOKING_ID, ROOM_NO , SUM(TOTAL) AS TOTAL FROM 
    (
     SELECT (END_DATE-START_DATE) DAYDIFF, ((END_DATE-START_DATE)*ROOM_PRICE) TOTAL_ROOM 
     FROM ROOM_TBL NATURAL JOIN ROOM_DETAILS_TBL WHERE BOOKING_ID = &BOOKING_ID 
    ) FROM ROOM_TBL; 

這是錯誤:

ERROR at line 3: 
ORA-00907: missing right parenthesis 
+1

太多櫨那裏,刪除後的最後一個) – 2013-03-20 17:53:45

+0

的我喜歡Oracle的東西是它將任何錯誤轉化爲「缺少括號」錯誤。我很確定,如果磁盤空間不足,你會得到'缺少括號'。 – 2013-03-20 17:55:36

回答

0

好你的幾個問題。

首先,在子查詢之前的查詢中有兩個FROM,子查詢之後有一個。

其次,你沒有GROUP BY,但你有一個聚合函數被使用。

它看起來像你可能想:

SELECT BOOKING_ID, ROOM_NO , SUM(TOTAL) AS TOTAL 
FROM 
(
    SELECT BOOKING_ID, 
     ROOM_NO, 
     (END_DATE-START_DATE) DAYDIFF, 
     ((END_DATE-START_DATE)*ROOM_PRICE) TOTAL 
    FROM ROOM_TBL 
    NATURAL JOIN ROOM_DETAILS_TBL 
    WHERE BOOKING_ID = &BOOKING_ID 
) 
GROUP BY BOOKING_ID, ROOM_NO; 

編輯,如果你想有一個TOTAL行,那麼你可以使用GROUP BY ROLLUP

SELECT max(BOOKING_ID) Booking_id, 
    case when ROOM_NO is null then ' ' else room_no end Room_no, 
    SUM(TOTAL) AS TOTAL 
FROM 
(
    SELECT BOOKING_ID, 
     ROOM_NO, 
     (END_DATE-START_DATE) DAYDIFF, 
     ((END_DATE-START_DATE)*ROOM_PRICE) TOTAL 
    FROM ROOM_TBL 
    NATURAL JOIN ROOM_DETAILS_TBL 
    WHERE BOOKING_ID = &BOOKING_ID 
) 
GROUP BY ROLLUP (room_no); 

SQL Fiddle with Demo

如果你想列中的數據,則可以在子查詢上使用公用表表達式:

with cte as 
(
    SELECT BOOKING_ID, 
     ROOM_NO, 
     (END_DATE-START_DATE) DAYDIFF, 
     ((END_DATE-START_DATE)*ROOM_PRICE) TOTAL 
    FROM ROOM_TBL 
    NATURAL JOIN ROOM_DETAILS_TBL 
) 
select booking_id, 
    room_no, 
    total, 
    case when rn = 1 then totalbooking else null end totalbooking  
from 
(
    select booking_id, 
     room_no, 
     total, 
     (select sum(total) from cte) TotalBooking, 
     row_number() over(partition by booking_id order by room_no) rn 
    from cte 
) 

SQL Fiddle with Demo

+0

有一些不請自來的建議:確保僅限日期(無時間分量)「ROOM_TBL.START_DATE」和「ROOM_TBL.END_DATE」,否則會得到一些非常奇怪的結果。不要相信其他程序員(或者你自己)爲了保持日期清潔。您可以使用檢查約束來強制執行此操作:'CHECK(END_DATE = TRUNC(END_DATE))'和類似的'START_DATE'。 – 2013-03-20 18:05:55

+0

我試圖以這種方式運行查詢,但仍然得到了同樣的錯誤: 錯誤在第7行: ORA-00907:缺少右括號 – user1909680 2013-03-20 19:25:41

+0

@ user1909680您可以使用表結構和一些示例數據編輯原始文章嗎? – Taryn 2013-03-20 19:26:52

0

雖然我不知道在你的架構中的各種屬性,試試這個:

SELECT z.BOOKING_ID, r.ROOM_NO , SUM(TOTAL) TOTAL 
FROM (SELECT ri.room_No, dt.Booking_id, 
      (END_DATE-START_DATE) DAYDIFF, 
      ((END_DATE-START_DATE)*ROOM_PRICE) TOTAL 
     FROM ROOM_TBL ri 
      NATURAL JOIN ROOM_DETAILS_TBL dt 
     WHERE BOOKING_ID = &BOOKING_ID) z 
    Join ROOM_TBL r 
    On r.ROOM_NO = z.Room_No