Сначала нашли людей, у которых есть ребенок, и сохраните их во временном столе вместе со своим ребенком. Потом нашли людей, у которых тоже есть ребенок.
SQL-скрипт:
-- Create table
CREATE TABLE #Family
(
id INT,
name VARCHAR(30),
surname VARCHAR(30),
dad_id INT,
mom_id INT
)
--insert data
INSERT INTO #Family (id, name, surname, dad_id, mom_id) VALUES (1, 'John', 'Smith', 2, 3)
INSERT INTO #Family (id, name, surname, dad_id, mom_id) VALUES (2, 'Arnold', 'Smith', 7, 8)
INSERT INTO #Family (id, name, surname, dad_id, mom_id) VALUES (3, 'Margaret', 'Smith', 5, 6)
INSERT INTO #Family (id, name, surname, dad_id, mom_id) VALUES (4, 'Junior', 'Smith', 1, 9)
-- Find people With child and save it into temporary table #FGTwo (family generation two)
SELECT * INTO #FGTwo FROM
(SELECT f.id, f.name, f.surname, f.dad_id, f.mom_id,
fd.id cid, fd.name cname, fd.surname csurname, fd.dad_id cdad_id, fd.mom_id cmom_id
FROM #Family f
INNER JOIN #Family fd ON fd.dad_id = f.id
UNION ALL
SELECT f.id, f.name, f.surname, f.dad_id, f.mom_id,
fm.id cid, fm.name cname, fm.surname csurname, fm.dad_id cdad_id, fm.mom_id cmom_id
FROM #Family f
INNER JOIN #Family fm ON fm.mom_id = f.id) AS FG2
--Uncomment next line to see people With their child
-- select * from #FGTwo
-- Find people With Grandchild and save it into temporary table #PeopleWithGrandchildren
SELECT * INTO #PeopleWithGrandchildren FROM
(SELECT f2.id, f2.name, f2.surname
from #FGTwo f2
INNER JOIN #Family fd ON fd.dad_id = f2.cid
UNION ALL
SELECT f2.id, f2.name, f2.surname
FROM #FGTwo f2
INNER JOIN #Family fm ON fm.mom_id = f2.cid) pwg
--Uncomment next line to see people With their child
-- select * from #PeopleWithGrandchildren
-- Finds all people having the same maximal number of grandchildren
DECLARE @MaxCount INT
SET @MaxCount = (SELECT TOP 1 COUNT(id) AS MaxCount FROM #PeopleWithGrandchildren GROUP BY id ORDER BY MaxCount DESC)
SELECT name, surname FROM #PeopleWithGrandchildren
WHERE id IN
(SELECT GC.id FROM
(SELECT id, COUNT(id) AS GCount FROM #PeopleWithGrandchildren GROUP BY id) GC
WHERE GCount = @MaxCount)
--If you want to select only one use the "SELECT TOP 1 " instead of "SELECT *"
-- drop all temporary tables
drop table #Family
drop table #FGTwo
drop table #PeopleWithGrandchildren
Выход:
name surname
Arnold Smith
Margaret Smith