简体   繁体   English

连接表中的列并合并具有相同ID的行

[英]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. 我正在处理SQL查询,但我完全迷失了联接。 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. 我的问题是来自单独表的行没有合并到具有相同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: 这是我的SQL语句:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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