Reputation: 5624
I'm working on a SQL query and I've completely lost myself in the joins. Hopefully you will be able to assist :)
My problem is that the rows from the separate tables are not merged into a single row where they all have the same id. Joins have been confusing to me for a long time so any assistance would be greatly appreciated.
I have the following tables:
Students
id
StudentCredits
sum_credits
StudentMandatoryCredits
branch_credits
program_credits
I'm trying to create a query that will give me rows like this:
id - sum_credits - branch_credits - program_credits
another_id - sum_credits - branch_credits - program_credits
a_third_id - sum_credits - branch_credits - program_credits
This is the best I can come up with though:
id - sum_credits - branch_credits - [empty]
id - sum_credits - [empty] - program_credits
This is my SQL statement:
SELECT S.id, SC.sum_credits, SMC.branch_credits, SMC.program_credits
FROM Students S
LEFT JOIN StudentCredits SC ON S.id = SC.id
LEFT JOIN StudentMandatoryCredits SMC ON S.id = SMC.id
ORDER BY id
Upvotes: 0
Views: 1905
Reputation: 28531
Try using:
SELECT S.id, SUM(SC.sum_credits), SUM(SMC.branch_credits), SUM(SMC.program_credits)
FROM Students S
LEFT JOIN StudentCredits SC ON S.id = SC.id
LEFT JOIN StudentMandatoryCredits SMC ON S.id = SMC.id
GROUP BY S.id
ORDER BY S.id
Upvotes: 3