SQL:对行条目数和连接数进行排序

时间:2015-09-16 18:57:07

标签: mysql sql

如何在列中找到重复的条目(如student_id列中的多个行),并将这些条目连接到具有公共ID的另一个表(如另一个表中的student_id以获取student_name)?

年级:

gcc -oer temp.cpp

生:

student_id,grade
6,A
1,B
1,F
7,C
6,A

这样我就可以在student_id,student_name 1,roy 6,bob 7,art 上找到一个只有重复学生行的联合表格,类似于:

student_id

然后返回最新数据框的名称会很好:

student_id,student_name,grade
6,bob,A
1,roy,B
1,roy,F
6,bob,A

2 个答案:

答案 0 :(得分:2)

试试这个:

select students.student_name
from grades 
inner join students on grades.student_id = students.student_id
group by student_name
having count(*) > 1

示例:

create table grades (student_id int, grade char(1));
insert into grades values (6, 'A'), (1, 'B'), (1, 'F'), (7, 'C'), (6, 'A');
create table students (student_id int, student_name varchar(20));
insert into students values (1, 'roy'), (6,'bob'), (7,'art');

select students.student_name
from grades 
inner join students on grades.student_id = students.student_id
group by student_name
having count(*) > 1

Result:
student_name
bob
roy

这应该导致鲍勃和罗伊。

Linux上的命令行,假设你有sqlite:

~$ sqlite
SQLite version 2.8.17
Enter ".help" for instructions
sqlite> create table grades (student_id int, grade char(1));
sqlite> insert into grades values (6, 'A');
sqlite> insert into grades values (1, 'B');
sqlite> insert into grades values (1, 'F');
sqlite> insert into grades values (7, 'C');
sqlite> insert into grades values (6, 'A');
sqlite>
sqlite> create table students (student_id int, student_name varchar(20));
sqlite> insert into students values (1, 'roy');
sqlite> insert into students values (6,'bob');
sqlite> insert into students values (7,'art');
sqlite>
sqlite> select students.student_name
   ...> from grades
   ...> inner join students on grades.student_id = students.student_id
   ...> group by student_name
   ...> having count(*) > 1;
roy
bob
sqlite>

答案 1 :(得分:1)

查找重复项,然后将其重新加入以获取更多信息:

SELECT s.student_id, s.student_name
FROM student s
INNER JOIN
   (SELECT g.student_id
    FROM grades g
    GROUP BY g.student_id
    HAVING COUNT(*) > 1) dups
 ON s.student_id = dups.student_id