简体   繁体   中英

Join columns from tables and merge rows with same id

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM