group by 练习

实验表创建

字段解释:
xh:学号
xh:姓名
nl:年龄

create table student(xh number,xm varchar2(4),nl int);
insert into student values(1,'A',21);
insert into student values(2,'B',21);
insert into student values(3,'A',21);
insert into student values(4,'A',21);
insert into student values(5,'A',21);
insert into student values(6,'C',21);
insert into student values(7,'B',21);

查看表

SQL> select * from student;

    XH XM           NL
---------- ------------ ----------
     1 A            21
     2 B            21
     3 A            21
     4 A            21
     5 A            21
     6 C            21
     7 B            21

7 rows selected.

SQL> 

问题与答案

问题:查询有重复的姓名
思路:使用count函数做统计,如果count >1,说明有重复

SQL> select xm,count(*) from student group by xm having(count(*) > 1);

XM         COUNT(*)
------------ ----------
A             4
B             2

SQL> 

问题:查询重复姓名学生的所有信息
*思路:select from student可以查看所有学生的信息,怎么查看重复的呢?上面我们已经知道了有哪些是重复的名字,那么我们只需要判断,哪些名字在重复的名字里面即可**

SQL> select * from student where xm in (select xm from student group by xm having(count(*) >1));

    XH XM           NL
---------- ------------ ----------
     1 A            21
     2 B            21
     3 A            21
     4 A            21
     5 A            21
     7 B            21

6 rows selected.

SQL>