SQL: how to sequence parent records by child rankings

Posted on 2008-10-07
Medium Priority
Last Modified: 2012-05-05
I am looking for some help in creating a simple SQL query to retrieve records from two related tables.

The tables (in simplified form) are as follows:

 primary_key integer,
 name varchar(20),
 PRIMARY KEY (primary_key)

 primary_key integer,
 parent_key integer,
 name varchar(20),
 age integer,
 PRIMARY KEY (primary_key)

I need to select records from the parent table that have at least one child, ordered by the age of the oldest child.

It seems a simple enough challenge but I have been unable to crack it. I hope somebody can help.

Many thanks,
Question by:Tim85
LVL 143

Accepted Solution

Guy Hengel [angelIII / a3] earned 500 total points
ID: 22657108
this should do:
select p.name, max(c.age) oldest_child_age
  from parent p
  join child c
    on c.parent_key = p.primary_key
 group by p.primary_key, p.name
 order by max(c.age) desc

Open in new window

LVL 37

Assisted Solution

momi_sabag earned 500 total points
ID: 22657109
select t1.name
from parent t1 inner join
 (select count(*) as cnt, max(age) as maxage, parent_key from child group by parent_key) t2
 on t1.primary_key = t2.parent_key)
order by t2.maxage desc

Author Closing Comment

ID: 31503728
Thanks to both of you for your extremely quick response. I have split the points, since each of you proposed a solution that works. Thanks again.

Featured Post

What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

When trying to connect from SSMS v17.x to a SQL Server Integration Services 2016 instance or previous version, you get the error “Connecting to the Integration Services service on the computer failed with the following error: 'The specified service …
During the weekend, I was asked to investigate into a deadlock in SQL Server 2014. SQL being something I don’t really fancy myself being an expert at, I had to do some refreshing. This article is a collection of my notes.
Via a live example, show how to shrink a transaction log file down to a reasonable size.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

569 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question