pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Nick Fankhauser <nickf@ontko.com>
To: PGSQL-SQL <pgsql-sql@postgresql.org>
Subject: Is there a more elegant way to write this query?...
Date: Mon, 10 Nov 2003 16:02:35 -0500
Message-ID: <NEBBLAAHGLEEPCGOBHDGCEAMJGAA.nickf@ontko.com> (raw)

Hi-

I'm suffering from a performance problem, but when I look at my query, I'm
not convinced that there isn't a better way to handle this in SQL. -So I'm
seeking advice here before I go to the performance list.

I have three tables- case, actor and actor_case_assignment.

As the names imply, actor_case_assignment contains records that assign an
actor to a case. Actors such as attorneys or judges may have many cases,
while the average actor (we hope) only has one.

What I'm trying to do is link these tables to get back a single row per
actor that shows the actor's name, the number of cases that actor is
assigned to, and if they only have one case, I want the number for that
case. This means I have to do some grouping to get the case count, but I'm
then forced to use an aggregate function like max on the other fields. I
hope there's a better way. Any suggestions?

Here's what I'm using right now:

  select
    actor.actor_id,
    max(actor.actor_full_name),
    max(case_data.case_public_id),
    max(case_data.case_id),
    count(case_data.case_id) as case_count
  from
    actor,
    actor_case_assignment,
    case_data
  where
    actor.actor_full_name_uppercase like upper('martin%')
    and actor.actor_id = actor_case_assignment.actor_id
    and case_data.case_id = actor_case_assignment.case_id
  group by
    actor.actor_id
  order by
    max(actor.actor_full_name),
    case_count desc,
  limit
    1000;


Thanks!
    -Nick

---------------------------------------------------------------------
Nick Fankhauser

    nickf@doxpop.com  Phone 1.765.965.7363  Fax 1.765.962.9788
doxpop - Court records at your fingertips - http://www.doxpop.com/





view thread (5+ messages)  latest in thread

Message-ID: <NEBBLAAHGLEEPCGOBHDGCEAMJGAA.nickf@ontko.com>
Permalink:  ../NEBBLAAHGLEEPCGOBHDGCEAMJGAA.nickf@ontko.com/
Also on:    postgresql.org/message-id/NEBBLAAHGLEEPCGOBHDGCEAMJGAA.nickf@ontko.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: nickf@ontko.com
  Subject: Re: Is there a more elegant way to write this query?...
  In-Reply-To: <NEBBLAAHGLEEPCGOBHDGCEAMJGAA.nickf@ontko.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox