group by 練習

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> 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章