views:

84

answers:

1

Hi I have a simple table with persons, but there is a additional
field witch holds information (person id) who is a father/mother
of that person, so the 2 dimensional table can hold a familly tree

the table is

id first_name  last_name salary spouse_id father_id mother_id sex
100 Steven King 26400 101 (null) (null) m  
101 Neena Kochhar 18700 100 (null) (null) f  
102 Lex De Haan 18700 106 100 101 m  
103 Alexander Hunold 9900 (null) 100 101 m  
104 Bruce Ernst 6600 (null) 102 106 m  
105 David Austin 5280 (null) 102 106 m  
106 Valli Pataballa 5280 102 (null) (null) f  
107 Diana Lorentz 4620 (null) (null) (null) f  
108 Nancy Greenberg 13200 109 (null) (null) f  
109 Daniel Faviet 9900 108 115 116 m  
110 John Chen 9020 (null) 109 108 m  
111 Ismael Sciarra 8470 (null) 109 108 m  
112 Jose Manuel Urman 8580 (null) 109 108 m  
113 Luis Popp 7590 (null) 109 108 m  
114 Den Raphaely 12100 (null) 109 108 m  
115 Alexander Khoo 3410 116 (null) (null) m  
116 Shelli Baida 3190 115 (null) (null) f  

The task is to select person name which has biggest number of grandchildren

All I managed to do is:

select 
e1.first_name, e1.last_name
--,max (e3.first_name)
,count(e3.first_name) grandchilds
from empnew e1
inner join
empnew e2
on (e1.id = e2.father_id)
inner join
empnew e3
on (e2.id = e3.father_id)
group by e1.first_name, e1.last_name

and the result is

first_name last_name grandchilds
Steven King 2
Alexander Khoo 5

please help :) ps: I would like to get RDBMS independent answer if it is possible

A: 

I think I did it, please take a look at my solution and comment it

SELECT 
e1.first_name
, e1.last_name
, count(e3.first_name) AS grandchilds
FROM empnew e1
INNER JOIN
empnew e2
ON (e1.id = e2.father_id)
INNER JOIN
empnew e3
ON (e2.id = e3.father_id)
GROUP BY e1.first_name, e1.last_name
HAVING COUNT(e3.first_name)
=
(SELECT MAX (grandchilds) FROM
(
SELECT 
e1.first_name
, COUNT(e3.first_name) AS grandchilds
FROM empnew e1
INNER JOIN
empnew e2
ON (e1.id = e2.father_id)
INNER JOIN
empnew e3
ON (e2.id = e3.father_id)
GROUP BY e1.first_name
) table_1);

edit: I fixed it up as 'onedaywhen' said

Marecky
Doesn't work on SQL Server (one of the most used SQL products) but can be fixed by giving your derived table a correlation name e.g. replace `))` with `) AS DT1 )`.
onedaywhen
...to be honest, if you want a SQL-product-independent answer, why aren't you writing SQL compliant with the SQL-92 Standard: upper case keywords (`SELECT` rather than `select`), using the `AS` keyword for correlation names (`empnew AS e1` rather than `empnew e1` and `COUNT(e3.first_name) AS grandchilds` rather than `count(e3.first_name) grandchilds`), ending statements with a semicolon `;`.
onedaywhen
to be honset I didn't know that! :)
Marecky