基于其他表的连接获取列的计数

vmpqdwk3  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(258)

我是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代码中获取表2中的学生id来获取学生的学分总和,并获取表2中找到的所有学生帐户id的所有学生帐户id和表1中的学分列的总和。我不知道如何加入或使这个查询简单。
通常我的方法是包含这两到三个不同的sql语句,但如果可能的话,我会在一个sql查询中查找这一点。
对于上面的例子,假设我想从第二个表中得到所有student\u acc\u id的学分总和,其中stu\u id是1011。我只有第一张table。所以输出应该是4+5,因为两个帐户属于同一个学生。
所以我需要:-->根据表2中的秒代码获取stu\u id(假设为tub秒代码)--->从表中获取所有stu\u id,其中stu\u id是上面语句的结果-->现在使用表1中所有student\u acc\u id的总和
感谢您的帮助!

qxsslcnc

qxsslcnc1#

像下面这样试试

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
vsaztqbk

vsaztqbk2#

根据现有数据使用join。但根据样本数据更好地从正确的表中获取数据。

select
    tab2.stud_id,
    SUM(tab1.credits) AS credit_sum
from
    table1 as tab1
    right join
        table2 as tab2
    on  tab1.student_acc_id = tab2.student_acc_id
    and tab1.sec_cd = tab2.sec_cd
where
    tab2.stud_id in(
        select distinct stud_id
        from table2
        where student_acc_id = '2098'
    )
group by
    tab2.stud_id;

您可以在这里查看其示例输出。请点击查看小提琴解决方案。

相关问题