我正在尝试查询酒店数据库以查找预订的总费用。我正在使用子选择查询但是我经常收到错误。
这是查询,我希望它显示预订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
答案 0 :(得分: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);
如果您想要列中的数据,那么您可以在子查询上使用公用表表达式:
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
)
答案 1 :(得分: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