显示度假胜地编号,度假胜地名称,预订数量和每个度假胜地收集的总金额

问题描述 投票:0回答:2

这是我写的查询:

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

如何添加具有相同度假村编号的总预订数?

sql database
2个回答
0
投票

您可以使用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;

0
投票

我认为您想将sum()totalcharge分别设为resortidresortname:因此,您只需要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的总和。

© www.soinside.com 2019 - 2024. All rights reserved.