what is the difference between group and having
give an example with query and sample output

Answer Posted / krishna murari chaubey

You Have two table person and friend
create table person(id int,pname varchar(20),gender varchar(3))
insert into person(id,pname,Gender)values(1,'krishna','m')
insert into person(id,pname,Gender)values(2,'Radha','f')
insert into person(id,pname,Gender)values(3,'Anamika','f')
insert into person(id,pname,Gender)values(4,'raj','m')
insert into person(id,pname,Gender)values(5,'suhani','f')
insert into person(id,pname,Gender)values(6,'ravi','m')

create table friend(id int,fid int)
insert into friend(id,fid)values(1,2)
insert into friend(id,fid)values(1,3)
insert into friend(id,fid)values(1,5)
insert into friend(id,fid)values(2,3)
insert into friend(id,fid)values(1,4)
insert into friend(id,fid)values(1,6)
insert into friend(id,fid)values(6,2)
insert into friend(id,fid)values(6,3)
insert into friend(id,fid)values(3,2)
insert into friend(id,fid)values(3,2)
insert into friend(id,fid)values(3,1)

find person who is male and having more than two female friend
Asnswer : -

select id,count(fid) as numberOfFemaleFriend from friend where fid in(select id from person where gender='f')
and id in (select id from person where gender='m' )
group by id having count(fid) >2

OR You can use Inner Join


select f.id,p.pname,count(f.fid) as numberOfFemaleFriend
from person p
inner join friend f
on p.id=f.id and p.gender='m' and f.fid in
(select id from person where gender='f')
group by f.id,p.pname having(count(f.fid)>2)

Is This Answer Correct ?    4 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

If any stored procedure is encrypted, then can we see its definition in activity monitor?

549


What is difference between join and natural join?

477


What is create command?

524


can an automatic recovery be initiated by a user? : Sql server administration

516


Your company has 50 branches all over the country all the branches, including the head office have sql server as the database every night all 50 branches upload certain information to the head office which replication topology is best suited for the above scenario?

627






Do you know what is difference between stored procedure and user defined function?

611


What is acid mean in sql server?

576


Can you explain what is indexed view? How to create it?

524


What is the use of set nocount on/off statement?

626


What are Spatial data types in SQL Server 2008

556


Can we check locks in database? If so, how can we do this lock check?

525


How many columns can we include on clustered index ?

511


How to fine-tune reports?

153


How many non clustered indexes there can be on table ?

509


How can you list all the columns in a database?

533