简体   繁体   English

SQL Sum 和 Groupby 语句返回错误/奇怪的数字

[英]SQL Sum and Groupby Statement return wrong/weird number

Let's get to the point:让我们进入正题:

My first query:我的第一个查询:

select hotel, sum(adult) from bookings 
group by hotel;

and it shows the correct sum number, but whenever I try to join with other table:它显示了正确的总和数,但每当我尝试加入其他表时:

select  b.hotel,    avg(r.hotelfacilities) as FacilitiesScore, 
                    avg(r.hotelservice) as ServiceScore, 
                    avg(r.hotelroom) as RoomScore, 
                    avg(b.rate) as PriceScore, 
                    sum(b.adult) as Persons
from bookings b join reviews r
on b.id = r.booking_id
group by b.hotel;

the number is weird and a lot bigger than it should be.这个数字很奇怪,而且比它应该的要大得多。 Where did I do wrong?我哪里做错了?

select  b.hotel,    
avg(r.hotelfacilities) as FacilitiesScore, 
avg(r.hotelservice) as ServiceScore, 
avg(r.hotelroom) as RoomScore, 
avg(b.rate) as PriceScore, 
sum(b.adult) as Persons
from bookings b join reviews r
group by b.hotel
on b.id = r.booking_id;

You are joining booking with reviews so eg if there is one booking with two reviews it gives you two rows.您正在加入带有评论的预订,例如,如果有一个带有两条评论的预订,它会给您两行。 Within group, that one booking became two rows which explains the weird (multiplied) values.在组内,一个预订变成了两行,这解释了奇怪的(相乘)值。 One solution is to calculate the aggregates separately then join the results:一种解决方案是分别计算聚合然后加入结果:

select *
from (
    select bookings.hotel
         , avg(b.rate) as PriceScore
         , sum(b.adult) as Persons
    group by bookings.hotel
) as booking_agg
join (
    select bookings.hotel
         , avg(reviews.hotelfacilities) as FacilitiesScore
         , avg(reviews.hotelservice) as ServiceScore, 
         , avg(reviews.hotelroom) as RoomScore, 
    from bookings
    join reviews on bookings.id = reviews.booking_id
    group by bookings.hotel
) as booking_review_agg on booking_agg.hotel = booking_review_agg.hotel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM