here is the sqlonline
There is a band.
Each member plays an instrument.
each instrument costs X$
I would like to create a report : how much each member ‘costs’ to the band manager.
create table #Inst(id int, name nvarchar(max) , price int )
insert into #Inst values (1,'guitar',20),
(2,'bass',10),
(3,'drums',30),
(4,'piano',40)
create table #Players(id int, name nvarchar(max) , instId int )
insert into #Players values (1,'john',1),
(2,'john',4),
(3,'paul',2),
(4,'paul',2),
(5,'george',1),
(6,'ringo',3)
What have I tried ?
select name , totalCostToTheband=
(select sum(price) from #inst i where i.id= #players.instId )
from #players
but this yields duplicate names :

I want to see 4 records which summarize each name’s costs.
p.s. :
I could have created a sum() over the whole query , but i want to know if there is a better , elegant solution.
In the current schema you should do
But when you have many-to-many relations you normally do a middle table with the links
This saves from duplicating the players inside the
#playerstable, and also allows for players with the same name to be in the same band 😉Read http://sqlrelationship.com/many-to-many-relationship/ for more info