Doubt in the elaboration of a query in SQL

Asked

Viewed 104 times

1

Could you tell me what’s wrong with this SQL code? I want for each film, the wages of each staff do not appear repeated, that is, if in the first film has 2 leads, in the table I want the sum of these values for the lead.

select Ms.salary as Total_salaries, R.title as papeis, M.title as filmes
from Movies M, Staff St, MovieStaff Ms, Roles R
where Ms.mvid=M.mvid
and Ms.stid=St.stid
and Ms.rid=R.rid
union 
select Ma.salary as Total_salaries, Ar.title as papeis_atores, M.title as filmes
from Movies M, Staff St, MovieActors Ma, ActorRoles Ar, Actors A
where Ma.mvid=M.mvid
and Ma.aid=A.aid
and A.aid=St.stid
and Ma.arid=Ar.arid;

So this doesn’t happen: inserir a descrição da imagem aqui

2 answers

1

In this case you must use an aggregation function sum(coluna) adding up the values in the column and the group by that groups the data by the columns that are selected except the one that is doing the calculation.

select sum(Ms.salary) as Total_salaries, R.title as papeis, M.title as filmes
from Movies M, Staff St, MovieStaff Ms, Roles R
where Ms.mvid=M.mvid
and Ms.stid=St.stid
and Ms.rid=R.rid
group by papeis, filmes
union 
select sum(Ma.salary) as Total_salaries, Ar.title as papeis_atores, M.title as filmes
from Movies M, Staff St, MovieActors Ma, ActorRoles Ar, Actors A
where Ma.mvid=M.mvid
and Ma.aid=A.aid
and A.aid=St.stid
and Ma.arid=Ar.arid
group by papeis, filmes;

I answered your question, but it’s good to study about group by: http://www.w3schools.com/sql/sql_groupby.asp

0

You can add salaries, but you can’t add movies and roles. You can see this on the link Laércio Lopes sent...

If you need some code, send the sql file with the tables used in the example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.