使用两个表进行分组操作

huangapple go评论51阅读模式
英文:

Using group by on two tables

问题

Student Subject name
stB114 English
stB114 English, Urdu
英文:

I have two tables. One is a subject and the other one is allocated subjects to students. What I need is to use GROUP BY and display all the students in a single column with all subjects.

Table: Subject_Selection

SubjectID Subject name
ITB001 English
ITB002 Urdu
ITB003 Math

Table: table Student with allocated subjects:

Stdid subject_id
stB001 ITB001
stB114 ITB001
stB114 ITB002

The Final output I want to use GROUP BY:

Student Subject name
stB114 English
stB114 English,Urdu

答案1

得分: 1

你可以使用inner join来连接数据,然后使用group bygroup_concat来将数据合并到单列中:

select s.Stdid as Student, group_concat(Subject_name) as 'Subject name'
from Student s
inner join Subject_Selection ss on s.subject_id = ss.SubjectID
group by s.Stdid

备注:这是适用于MySQL/MariaDB的有效解决方案。如果您使用其他的数据库管理系统,您需要将group_concat更改为等效的函数。

演示在这里

英文:

You can do it using inner join to join data and group by with group_concat to combine data in single column :

select s.Stdid as Student, group_concat(Subject_name) as 'Subject name'
from Student s
inner join Subject_Selection ss on s.subject_id = ss.SubjectID
group by s.Stdid

Ps : this is a working solution for mysql/mariadb

If your are using an other dbms then you have to change group_concat by an equivalent.

Demo here

答案2

得分: 0

STEP 1: - 根据 subject_id 将两个表连接,以便获取学生 ID、学科名称和 subject_id 放在一个元组中。

STEP 2: - 只需按学生 ID 进行分组,将特定组中的不同元组连接成一个单一元组...

选择 Stdid 作为学生,group_concat(Subject_name) 作为 'Subject name' 从 Student NATURAL JOIN Subject_Selection 分组按 Stdid;

演示:-
https://dbfiddle.uk/-YoftCWl

我使用了自然连接,因为我在两个表中都将属性名称更改为 SubjectID;否则,您可以使用内连接。

英文:

STEP 1:-JOIN the 2 tables on subject_id so that you get student id and subject name and subject_id on a single tuple.

STEP 2:- just group by student_id and concat the different tuples in a particular group to a single tuple...

select Stdid as Student, group_concat(Subject_name) as 'Subject name' from Student NATURAL JOIN Subject_Selection group by Stdid;

DEMO:-
https://dbfiddle.uk/-YoftCWl

I used natural join since I changed the attribute name to SubjectID in both the tables; otherwise you can use inner join

huangapple
  • 本文由 发表于 2023年3月9日 21:39:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75685377.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定