Re: Problem with phone list.

From: Michael Glaesemann <grzm(at)seespotcode(dot)net>
To: Mike Diehl <jdiehl(at)sandia(dot)gov>
Cc: "SQL Postgresql List" <pgsql-sql(at)postgresql(dot)org>
Subject: Re: Problem with phone list.
Date: 2007-08-15 21:04:37
Message-ID: 904C5251-F9A7-4579-B083-F77DDB4D6EDC@seespotcode.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql


On Aug 15, 2007, at 15:28 , Mike Diehl wrote:

> I've got a table, actually a view that joins 3 tables, that
> contains a phone
> number, a unique id, and a call duration.
>
> The phone number has duplicates in it but the unique id is unique.
>
> I need to get a list of distinct phone numbers and the
> coorisponding largest
> call duration.

If you don't need the id, the simplest thing to do is just

SELECT phone_number, max(call_duration)
FROM calls
GROUP BY phone_number;

However, I assume you want the id as well. My first thought is to use
PostgreSQL's DISTINCT ON (if you don't mind using non-SQL-standard
syntax):

SELECT DISTINCT ON (phone_number)
phone_number, call_duration, id
FROM calls
ORDER BY phone_number
, call_duration DESC;

Another way is to figure out the maximum duration for each phone
number and join this back to the full list.

SELECT id, phone_number, call_duration
FROM calls
NATURAL JOIN (
SELECT phone_number, max(call_duration) as call_duration
FROM calls
GROUP BY phone_number
) max_call_durations_per_number;

Two caveats: this either potentially returns more than one id per
phone number (if more than one call with the same phone number has
the same duration, which is also the max). If you add a DISTINCT (and
ORDER BY) to the subquery, you could get distinct numbers, but
potentially miss information.

Michael Glaesemann
grzm seespotcode net

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Tom Lane 2007-08-15 21:48:19 Re: Boolean without default declared
Previous Message Richard Broersma Jr 2007-08-15 21:00:05 Re: Problem with phone list.