mysql - 根据来自其他表的连接获取列的计数
问题描述
我是 SQL 新手。我必须表格并尝试从表 1 中获取列数并通过表 2 中的其他列加入。
表格1:
credits | sec_code | student_acc_id
--------------------------------
4 TUB 2098
5 JIY 2099
6 THG 3011
表 2:
id| sec_code | student_acc_id | stu_id
-------------------------------------
1 TUB 2098 1011
5 JIY 2099 1011
7 THG 3011 1012
我想通过从 sec_code 获取 table2 的 stu_id 来获得学生的学分总和,并获取 stuId 的所有 student_acc_id 并为从表 2 中找到的所有学生帐户 ID 求和 table1 中的学分列。我不知道如何我们可以加入或简化这个查询吗?
通常我的方法是包含这两到三个不同的 SQL 语句,但如果可能的话,我会在一个 sql 查询中寻找它。
对于上面的示例,假设我想从第二个表中获取所有 student_acc_id 的学分总和,其中 stu_id 为 1011。我只有第一张桌子。所以输出应该是 4+5,因为两个账户都属于同一个学生。
所以我需要:->根据表二中的sec_code获取stu_id(让我们说TUB sec_code)->从表中获取所有student_acc_id,其中stu_id是上述语句的结果->现在使用所有student_acc_id的总和表格1
任何帮助表示赞赏!
解决方案
尝试如下
select t2.stu_id,
sum(t1.credits)
from t1 join t2 on t1.student_acc_id=t2.student_acc_id and
t1.sec_code=t2.sec_code
group by stu_id
Having count(stu_id)>1
推荐阅读
- javascript - React 如何监听状态变化
- r - 如何从 R 中的数字高程模型绘制高程?
- python-3.x - Python guilds.join Discord OAuth2 的麻烦
- ansible - 如何运行剧本并指向不同但新定义的 groupvar?
- gekko - 对可以在时间范围内使用有限次且也是二进制的输入进行建模
- python-3.x - ValueError:无法将字符串转换为浮点数:(pd.Series)
- php - 如何在 CodeIgniter 中添加指向路由的链接?
- node.js - crypto.createHmac 失败,字符串如 "face_url":"https\/\/"'
- ios - Flutter 中的新版 Google Maps SDK
- javascript - 定义浏览器性能的 Javascript 函数