tags:

views:

38

answers:

1

Given table USER (name, city, age), what's the best way to get the user details of oldest user per city?

I have seen the following example SQL used in Oracle which I think it works

select name, city, age 
from USER, (select city as maxCity, max(age) as maxAge 
            from USER 
            group by city)
where city=maxCity and age=maxAge

So in essence: use a nested query to select the grouping key and aggregate for it, then use it as another table in the main query and join with the grouping key and the aggregate value for each key.

Is this the standard SQL way of doing it? Is it any quicker than using a temporary table, or is in fact using a temporary table interanlly anyway?

A: 

What you are using will work, although it displays all users which share the max age.

You can do this in a slightly more readable way using the row_number() ranking function:

select name, city, age 
from (
    select 
        city
     ,  age
     ,  row_number() over (partition by city order by age) as rn
     from USER
) sub
where rn = 1

This will also select at most one user per city.

Most database systems will use a temporary table to store the inner query. So I don't think a temporary table would speed it up. But database performance is notoriously hard to predict from a distance :)

Andomar
right, this works in oracle too (apart from missing "name" in subquery typo), so I guess row_number() and partition are standard SQL? (i mean, I will be able to use them in sybase and maybe MySQL)Also I'd like to confirm whether using subqueries in the FROM clause is standard and portable In my case I wanted to get all matching rows, so i'll stick to my option, but this is a good one too.
@xulochavez: Subqueries in the FROM clause are very portable. The ranking functions are not, I think they're limited to SQL Server, Oracle and PostgreSQL. Definitely not MySQL
Andomar