Click here to Skip to main content
16,022,362 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i have a table called ticket

id Name PartId
1 great 3
2 wonder 2
3 great 2


and another table called
Table part

partId Amount
1 300
2 500
3 600
4 700

The table above is a demo of how my table looks like. What i want to achieve by querying both table is this


Name total TotalAmount
Great 2 1100


Note: My total amount is gotten by adding the amount for PartId "2 and 3" together. I hope this explains my challenge very well. How do i acheive this using sql?

What I have tried:

i have tried to group By in my query but not getting desired result
Posted
Updated 21-Nov-16 23:25pm
Comments
Kornfeld Eliyahu Peter 21-Nov-16 8:32am    
And why 2 and not 3 on the second column?
Andy Lanng 21-Nov-16 8:35am    
are you aware of joins and aggregates? If you're not then I find it hard to believe that is a real world problem and not an assignment.
Andy Lanng 21-Nov-16 8:37am    

You need to use a GROUP BY and a JOIN to get the info:
SQL
SELECT t.Name, SUM(p.Amount) FROM Ticket t
JOIN Part p ON t.PartId = p.partId
GROUP BY t.Name
 
Share this answer
 
select tk.Name,count(tk.Name) as total,sum(amount) totalamount from @ticket tk
join @Part pt on tk.partid=pt.partid
group by tk.Name;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900