Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

The most children

Status
Not open for further replies.

SimonTheSponge

Programmer
Feb 12, 2001
74
GB
Having a bit of mind going blank day

I have a parent table

Member
Membership_no (char(10)) PK
First_name (char(30))
Surname (char(30))

and a child table

Role_no (char(10)) PK
Membership_no (char(10)) FK
...and various other fields

I want a query to return the membership_no, first_name, surname and the number of roles they have for the member with the most roles and . This is running SQL 6.5

Cheers
 
select A.membership_no, A.First_Name, A.SurName, B.Cnt as RoleCnt
from #Member A join
(
select top 1 membership_no,count(distinct role_no) as Cnt from #Role group by membership_no order by Cnt desc
) B
on A.membership_no = B.membership_no

-Manjari
 
Select Membership_no, First_name, Surname, Count(Role_no)

From Member

Inner Join Table2 On Table2.Membership_no = Member.Membership_no

Group By Membership_no, First_name, Surname
 
manjarikosaraju, unfortunately Top x is not available in SQL Server 6.5 which is where I'm having problems at the moment ;-)

 
Is this what you want?

Code:
SET ROWCOUNT 1

SELECT m.memberid, m.firstname, m.surname, COUNT(*) AS roles
FROM member m JOIN role r ON m.memberid = r.memberid
GROUP BY m.memberid, m.firstname, m.surname
ORDER BY COUNT(*) DESC

SET ROWCOUNT 0

--James
 
I am not very familiar with SQL Server 6.5 syntax

Try this:

Declare @MaxCnt int
select @MaxCnt = max(x.Cnt)
from (select membership_no, count(distinct role_no) as Cnt from #Role group by membership_no) x

select A.membership_no, A.First_Name, A.SurName, @MaxCnt as RoleCnt
from #Member A join #Role B on A.membership_no = B.membership_no
group by A.membership_no,A.First_Name, A.SurName
having count(distinct role_no) = @MaxCnt

Hope this helps.

-Manjari
 
LOL, I'm almost tempted to give you a star for a great bit of lateral thinking James. Unfortunately it is possible for there to be more than one member sharing the most number of roles in which case I'd like both/all reported ;-)

Thanks Manjarikosaraju this has given me a pointer

Could you not achieve it with the single statement

select A.membership_no, A.First_Name, A.SurName, count(*) as RoleCnt
from #Member A join #Role B on A.membership_no = B.membership_no
group by A.membership_no,A.First_Name, A.SurName
having count(*) = (select max(x.Cnt)
from (select membership_no, count(distinct role_no) as Cnt from #Role group by membership_no) x)



Cheers
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top