Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to retrieve records which occurred more than twice in oracle?

I have this table

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

and this as data

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

so i wanted to retrieve records which has occurred more than twice. my code is

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

the result was perfect.

but when i want s_subject as well it says no rows selected. I dont know why.

select stu_id,s_Name,s_subject 
from student 
group by stu_id,s_Name,s_subject 
having count(stu_id) >2 ;
like image 895
Ashish dmc4 Avatar asked Mar 06 '12 11:03

Ashish dmc4


People also ask

How do you check if value appears more than once in SQL?

To find duplicate values in SQL, you must first define your criteria for duplicates and then write the query to support the search. In order to see how many of these names appear more often than others, you could add an additional ORDER BY statement to the end of the query and order by DESC.

How do I fetch more than 1000 records in SQL?

To query more than 1000 rows, there are two ways to go about this. Use the '$offset=' parameter by setting it to 1000 increments which will allow you to page through the entire dataset 1000 rows at a time. Another way is to use the '$limit=' parameter which will set a limit on how much you query from a dataset.


1 Answers

It's because none of your students have more than one record per subject.

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

This code asks for records that occur more than twice that have the same Student ID, name and subject. None of the records in your sample meet this.

If, however, what you actually want is the ID, name and subjects of any student that is taking more than two classes, this can accomplished quite easily.

Using a slightly modified version of your initial SQL as a filter, we get this:

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

Hope this helps.

like image 152
John N Avatar answered Nov 08 '22 20:11

John N