I'm new to sql and I'm practicing on a created database in oracle about airbnb listings in amsterdam and berlin. I'm trying to JOIN the Tables HOSTS (host_id, host_name), LISTINGS (which includes all listings in the two city with the attributes listings_id, listings_name, Price, host_id...), Neighbourhoods (Neighbourhood_Group, City and Neighbourhood) and reviews (with review_id, listings_id as a foreign key, reviewer_id, reviewer_name and comment).
Now i want to write a query, which returns the average price, lowest price, highest price, the city (Berlin or Amsterdam), the neighbourhood (Centrum, Alexanderplatz...), the amount of listings and the amount of reviews, all grouped by the distinct neighbourhood, and by the WHERE statement, that limits the returns to those listings, that are hosted by Hosts which have less than 3 listings total.
Now if I run the query without the reviews table and only order it by amount_listings, I get the correct amount of listings per neighbourhood for the column "amount_listings".
SELECT avg(l.price) as Mean_Price,
n.city,
n.neighbourhood,
count (l.listings_id) as amount_listings,
min(l.price),
max(l.price)
FROM listings l
INNER JOIN neighborhood n
ON l.neighbourhood = n.neighbourhood
INNER JOIN hosts h
ON l.host_id = h.host_id
WHERE h.host_id IN (
SELECT host_id
FROM listings
GROUP BY host_id
HAVING count(host_id) < 3
)
GROUP BY n.neighbourhood, n.city
ORDER BY amount_listings DESC;
But if i include the amount of reviews in the query, the results are incorrect. The amount of reviews and the amount of listings column show the wrong amount (too much).
SELECT avg(l.price) as Mean_Price, count(l.listings_id) as amount_listings,
min(l.price), max(l.price), n.city, n.neighbourhood, count(r.review_id) as amount_reviews
FROM listings l
INNER JOIN neighborhood n
ON l.neighbourhood = n.neighbourhood
INNER JOIN hosts h
ON l.host_id = h.host_id
INNER JOIN reviews r
ON l.listings_id= r.listings_id
WHERE h.host_id IN (
SELECT host_id
FROM listings
GROUP BY host_id
HAVING count(host_id) < 3
)
GROUP BY n.neighbourhood, n.city
ORDER BY amount_listings DESC, amount_reviews DESC;
I dont know why the amount_listings and amount_reviews return such wrong results.