mySQL Using Average with Group By Function - mysql

I need to find the average price of a movie by genre.
The tables are Movie (movie_genre) and Price (price_rentfee)
I tried:
select movie_genre, avg(price_rentfee)
from movie, price
group by movie_genre;
It lists the movie's by genre with the avg rental fee,
but the average rental fee is the same for all of them.
Is there a way where I can average it out by genre?

Your query says
FROM movie, price
That's probably a mistake. It generates every possible combination of movie and price. You probably need something like this instead to get useful results.
FROM movie
JOIN price ON movie.movie_id = price.movie_id

your query need key column to join both of tables.
select movie_genre, avg(price_rentfee) as avgPrice
from movie, price
where movie.movie_id = price.movie_id
group by movie_genre;
or
select movie_genre, avg(price_rentfee) as avgPrice
from movie
Left Join price
on price.movie_id = movie.movie_id
group by movie_genre;

Turns out I was missing a join, group by, and having clause. Answer i was looking for was
select movie_genre, avg(price_rentfee)
from price
right join movie
on price.price_code = movie.price_code group by movie_genre;
Sorry for the ambiguous question and thanks for the help.

Related

How do add data to multiple columns at the same time

I got this last task before I can go to bed...
Make a query that shows the name(not the id) of players who have won the lottery more than once, how many times they've won and the name(not the id) of the municipality they live in.
Players-table: PlayerNum, Name, Address, MunicipalityID
Winners-table: PlayerNum, DrawID
Municipality-table: MunicipalityID, County, Population, Name
Thank you sooo much in advance!!
You need to join the tables and do a sub query on the winner table using count and group by the join the result set with player
Not sure what the draw table does
You really should make an attempt instead of just asking for the solution.
Your starting point is to find the users who have won more than once. This is a simple GROUP BY of PlayerNum and the HAVING clause to limit the result based on the COUNT -
SELECT PlayerNum, COUNT(DrawID) AS num_wins
FROM Winners
GROUP BY PlayerNum
HAVING num_wins > 1
The next step is to add the names of the players. For this you need to join to the Players table and I have added table aliases (w & p) to avoid retyping the full table name each time -
SELECT p.Name, COUNT(DrawID) AS num_wins
FROM Winners w
INNER JOIN Players p
ON w.PlayerNum = p.PlayerNum
GROUP BY w.PlayerNum
HAVING num_wins > 1
And then finally the join to Municipality to get the Name with a column alias as we already have a Name column -
SELECT p.Name, COUNT(DrawID) AS num_wins, m.Name AS MunName
FROM Winners w
INNER JOIN Players p
ON w.PlayerNum = p.PlayerNum
INNER JOIN Municipality m
ON p.MunicipalityID = m.MunicipalityID
GROUP BY w.PlayerNum
HAVING num_wins > 1

Use SELECT through three table

I tried to write a query, but unfortunately I didn't succeed.
I want to know how many packages delivered over a given period by a person.
So I want to know how many packages were delivered by John (user_id = 1) between 01-02-18 and 28-02-18. John drives another car (another plate_id) every day.
(orders_drivers.user_id, plates.plate_name, orders.delivery_date, orders.package_amount)
I have 3 table:
orders with plate_id delivery_date package_amount
plates with plate_id plate_name
orders_drivers with plate_id plate_date user_id
I tried some solutions but didn't get the expected result. Thanks!
Try using JOINS as shown below:
SELECT SUM(o.package_amount)
FROM orders o INNER JOIN orders_drivers od
ON o.plate_id=od.plate_id
WHERE od.user_id=<the_user_id>;
See MySQL Join Made Easy for insight.
You can also use a subquery:
SELECT SUM(o.package_amount)
FROM orders o
WHERE EXISTS (SELECT 1
FROM orders_drivers od
WHERE user_id=<user_id> AND o.plate_id=od.plate_id);
SELECT sum(orders.package_amount) AS amount
FROM orders
LEFT JOIN plates ON orders.plate_id = orders_drivers.plate_id
LEFT JOIN orders_driver ON orders.plate_id = orders_drivers.plate_id
WHERE orders.delivery_date > date1 AND orders.delivery_date < date2 AND orders_driver.user_id = userid
GROUP BY orders_drivers.user_id
But seriously, you need to ask questions that makes more sense.
sum is a function to add all values that has been grouped by GROUP BY.
LEFT JOIN connects all tables by id = id. Any other join can do this in this case, as all ids are unique (at least I hope).
WHERE, where you give the dates and user.
And GROUP BY userid, so if there are more records of the same id, they are returned as one (and summed by their pack amount.)
With the AS, your result is returned under the name 'amount',
If you want the total of packageamount by user in a period, you can use this query:
UPDATE: add a where clause on user_id, to retrieve John related data
SELECT od.user_id
, p.plate_name
, SUM(o.package_amount) AS TotalPackageAmount
FROM orders_drivers od
JOIN plates p
ON o.plate_id = od.plate_id
JOIN orders o
ON o.plate_id = od.plate_id
WHERE o.delivery_date BETWEEN convert(datetime,01/02/2018,103) AND convert(datetime,28/02/2018,103)
AND od.user_id = 1
GROUP BY od.user_id
, p.plate_name
It groups rows on user_id and plate_name, filter a period of delivery_date(s) and then calculate the sum of packageamount for the group

seems that my where statement in sql is being ignored?

i have a query that returns a score for each item listed in a table that has the year earlier than 1980. I have a similar one for years after 1980. when i try to compute the average of one minus the average the other, it for some reason is computing the averages as the same (so as to be ignoring my where clause. am i doing something wrong?
Select avg(stars)
from
(Select stars
from Rating, Movie
where movie.mid = rating.mid and movie.year < 1980);
Change your cartesian product join to a regular join would be the first step... we need to see some data to understand the question better... but heres a first pass
SELECT AVG(stars)
FROM movie
JOIN rating ON rating.mid = movie.mid
WHERE movie.year < 1980
GROUP BY movie.mid
if this doesn't work then please post some data so I can test it

Joining multiple issue

I am really having trouble joining mulitple tables in a working query.
There are 5 different tables:
Event storing: eventid, staffnumber, date, start and end date..
Event_overview storing: eventid, clientid..
Rates storing: clientid, rateswaiter, rateschef, ratesteamleader..
staff: staffid, firstname, lastname..
salary: staffid, salary
I want to create one table giving me the result for all events grouped by staffid indicating the total number of hours they worked per event, the rate according to their role per hour and multiplied by the number of hours they worked, the salary, salary*hours
I have started with two different tables which work perfectly on their own.
Select event.staffid, staff.firstname,
staff.lastname, salary.wage, evento.clientid,
event.date, TIMEDIFF( hours, pause ) AS Total, event.role
from event
inner join evento on event.eventid=evento.eventid
inner join salary on event.staffid=salary.staffid
inner join staff on event.staffid=staff.staffid
The second query
SELECT event.clientid
FROM evento
JOIN rates ON evento.clientid = rates.clientid
group by evento.clientid
Later I want need to decide which rate to select based on the role of the staff member
CASE WHEN Position = 'Teamleader'
THEN (Teamleader)
WHEN Position = 'waiter'
THEN (waiter)
WHEN Position = 'chef'
THEN (chef)
ELSE '0'
END AS revenue
I want to have those information in one table so I can start mulitpliying and summing up per staff member and using above queries as subqueries.
Hope someone can help me.
thanks in advance,
I think something like this is what you want:
Select event.staffid, staff.firstname,
staff.lastname, salary.wage, evento.clientid,
event.date, TIMEDIFF( hours, pause ) AS Total, event.role,
TIMEDIFF(hours, pause) *
case position
when 'Teamleader' then rateteamleader
when 'waiter' then ratewaiter
when 'chef' then ratechef
end TotalSalary
from event
inner join evento on event.eventid=evento.eventid
inner join salary on event.staffid=salary.staffid
inner join staff on event.staffid=staff.staffid
inner join rates on evento.clientid = rates.clientid
It would be better if you normalized the rates table, with columns: clientid, position, rate. Then the join would be:
inner join rates on evento.clientid = rates.clientid and staff.position = rates.position
and you would just do TIMEDIFF(house, pause) * rate to get TotalSalary.

fetch some data from two tables

i have site like imdb and we provide movie information sin site..and our website have option to rate all movies for every users.
I have two tables
1 . imdb (its for store movie details)
id,name,actors,vote
2. ratings (its for store users rating details) id,rating_id(its same as id from first table),rating_num,IP
now what am doing is..when anyone rating a movie take the avg of that movie rating by using rating tables (total ratings/number of ratings) and insert that value into "vote" column in first table..my demands this..thats why done like this..
Now my problem is..i want to fetch top rated movies..i mean in vote column which movie have top rating which want to list and one more condition is that that movie should rated by 10 users(use ratings table for that)
thanks in advance
I don't quite understand how your tables are organized. Is there A) a new row for each rating given by a customer in the ratings table or B) is there only 1 row per movie which is updated?
I am gues it is A and rating_num is the rating given by the costumer.
In this case, a simple MySql solution could make use of aggregate functions such as COUNT and AVG. Untested example.
EDIT - To get the details from the imdb table you will just need to join them.
SELECT id as 'ID', COUNT(1) as 'Number of ratings', AVG(r.rating_num) as 'Average rating', i.name, i.actors, i.vote
FROM ratings r
INNER JOIN imbd i ON ( r.id = i.id )
GROUP BY r.id
HAVING `Number of ratings` >= 10
ORDER BY `Average rating` desc
LIMIT 10