【问题标题】:how to retrieve records which occurred more than twice in oracle?如何检索在oracle中出现两次以上的记录?
【发布时间】:2012-03-23 20:42:32
【问题描述】:

我有这张桌子

create table student (
   stu_id int,
   s_name nvarchar(max),
   s_subject nvarchar(max),
)

这是数据

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';

所以我想检索发生两次以上的记录。我的代码是

select stu_id,s_Name 
from student 
group by stu_id,s_Name 
having count(stu_id) >2 ;

结果很完美。

但是当我想要s_subject 时,它说没有选择行。我不知道为什么。

select stu_id,s_Name,s_subject 
from student 
group by stu_id,s_Name,s_subject 
having count(stu_id) >2 ;

【问题讨论】:

  • 您只需要选择主题,对吗?仅当 stu_id,s_Name 重复时才会重复,对吗?如果是这样,你想得到哪个科目?不止一个...

标签: sql oracle sqlplus


【解决方案1】:

这是因为您的学生每个科目的记录都不超过一条。

select stu_id,s_Name,s_subject 
from student 
group by stu_id,s_Name,s_subject 
having count(stu_id) >2 ;

此代码要求提供两次以上具有相同学生 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 );

希望这会有所帮助。

【讨论】:

  • 实际上我没有使用 IN 而是使用返回超过 1 行的子查询。谢谢。
【解决方案2】:

当您按表中存在的所有列进行分组时,它将生成唯一的行(具有一个频率行的记录)。由于您已经选择了超过 2 的行,它不会有频率为 2 的记录。 如果您使用 count=1,您将获得所有 count=1 的行,

select stu_id,s_Name,s_subject 
from student 
group by stu_id,s_Name,s_subject
having count(stu_id) =1 ;

输出将是:

stu_id      s_Name      s_subject
   ----------- -------------
123         pammy       Chemistry
123         pammy       English
123         pammy       Maths
124         watts       Biology
125         Tom         Computer
125         Tom         ED
125         Tom         Physics

【讨论】:

    猜你喜欢
    • 2018-12-31
    • 2020-04-12
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多