这是我写的查询:
1 select resort.resortid,resort.resortname,(count(booking.bookingid)) as
2 "TOTALBOOKING" ,booking.totalcharge as "TOTALAMOUNT" from resort join booking on
3 booking.resortid=resort.resortid
4 group by resort.resortid,resort.resortname,booking.totalcharge
5 order by resort.resortid;
和输出:
RESORTID RESORTNAME TOTALBOOKING TOTALAMOUNT
1001 TREE OF LIFE RESORT 1 30000
1001 TREE OF LIFE RESORT 1 48000
1002 PALETTE RESORTS 1 30000
1003 GRAND GRT 1 32000
1004 GREEN COCONUT 1 30000
预期输出:RESORTID RESORTNAME TOTALBOOKING TOTALAMOUNT
1001 TREE OF LIFE RESORT 2 78000
1002 PALETTE RESORTS 1 30000
1003 GRAND GRT 1 32000
1004 GREEN COCONUT 1 30000
如何添加具有相同度假村编号的总预订数?
您可以使用count()
的窗口版本。
SELECT resort.resortid,
resort.resortname,
count(booking.bookingid) AS "TOTALBOOKING",
booking.totalcharge AS "TOTALAMOUNT",
count(booking.bookingid) OVER (PARTITION BY resort.resortid) AS "totalbookings having same resortid"
FROM resort
INNER JOIN booking
ON booking.resortid = resort.resortid
GROUP BY resort.resortid,
resort.resortname,
booking.totalcharge
ORDER BY resort.resortid;
我认为您想将sum()
和totalcharge
分别设为resortid
和resortname
:因此,您只需要group by
子句中的后两列(而不是totalcharge
)。
select
r.resortid,
r.resortname,
count(*) totalbooking ,
sum(b.totalcharge) as totalamount
from resort r
inner join booking b on b.resortid = r.resortid
group by r.resortid, r.resortname
order by r.resortid;
请注意,表别名使查询更易于编写和读取。
这使您每个度假胜地都有一行,其中包括预订总数和totalcharge
的总和。