那么你有几个问题。
首先,查询中有两个FROM
s,一个在子查询之前,一个在子查询之后。
其次,你没有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 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