Ash*_*mc4 9 sql oracle sqlplus
我有这张桌子
create table student (
stu_id int,
s_name nvarchar(max),
s_subject nvarchar(max),
)
Run Code Online (Sandbox Code Playgroud)
这是数据
insert into student values(123,'pammy','English');
insert into student values(123,'pammy','Maths');
insert into student values(123,'pammy','Chemistry');
insert into student values(124,'watts','Biology');
insert into student values(125,'Tom','Physics');
insert into student values(125,'Tom','Computer';
insert into student values(125,'Tom','ED';
Run Code Online (Sandbox Code Playgroud)
所以我想检索已发生两次以上的记录.我的代码是
select stu_id,s_Name
from student
group by stu_id,s_Name
having count(stu_id) >2 ;
Run Code Online (Sandbox Code Playgroud)
结果很完美.
但是当我想要s_subject它时也没有选择任何行.我不知道为什么.
select stu_id,s_Name,s_subject
from student
group by stu_id,s_Name,s_subject
having count(stu_id) >2 ;
Run Code Online (Sandbox Code Playgroud)
Joh*_*n N 26
这是因为没有一个学生每个科目有多个记录.
select stu_id,s_Name,s_subject
from student
group by stu_id,s_Name,s_subject
having count(stu_id) >2 ;
Run Code Online (Sandbox Code Playgroud)
此代码要求出现两次以上具有相同学生ID,姓名和主题的记录.您的样本中的所有记录都不符合此要求.
但是,如果您真正想要的是任何学生参加两个以上课程的ID,姓名和科目,这可以很容易地完成.
使用稍微修改过的初始SQL版本作为过滤器,我们得到:
select stu_id, name, subject
from student
where stu_id in ( select stu_id
from student
group by stu_id
having count(stu_id) >2 );
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.