标识bamount高于bamount之和的目标

b4lqfgs4  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(224)
select destname from destination where destinationid in (select destinationid from booking group by destinationid having bookamount> (select avg(bookamount) from booking));

执行之后,它向我显示错误的输出。在那之后我试过这个。通过此查询,我可以获得每个目的地的平均金额,现在我需要知道单个预订金额大于该地点平均完成金额的目的地:

select destinationid, avg(bookamount) from booking group by destinationid;

但我需要一个正确的建议。
我试过硬编码,但我知道这样做是错误的:

cs7cruho

cs7cruho1#

是否要查找超过目的地平均金额的预订?

SELECT b.*
FROM booking b
    INNER JOIN (
        -- Make a subquery (think of it as a helper table) to look up the average booking amount for each destination.
        SELECT destination_id, AVG(book_amount) AS book_amount_avg FROM booking GROUP BY destination_id
    ) AS da
        ON b.destination_id = da.destination_id
WHERE b.book_amount > da.book_amount_avg
rqcrx0a6

rqcrx0a62#

那么这个怎么样?

SELECT d.destination_id, d.name
FROM destination d
    INNER JOIN (
        -- Total value bookings for each destination.
        SELECT destination_id, SUM(booking_amount) AS booking_amount_destination_sum 
        FROM booking 
        GROUP BY destination_id
    ) AS dt
        ON d.destination_id = dt.destination_id
    INNER JOIN (
        -- Averave value of bookings for each location.
        SELECT location_id, AVG(book_amount) AS book_amount_location_avg 
        FROM booking 
        GROUP BY location_id
    ) AS la
        ON d.location_id = la.location_id
WHERE dt.booking_amount_destination_sum > da.book_amount_location_avg

相关问题