Re: GROUP BY on a column which might exist in one of two tables

From: hubert depesz lubaczewski <depesz(at)depesz(dot)com>
To: Mark Stosberg <mark(at)summersault(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: GROUP BY on a column which might exist in one of two tables
Date: 2008-06-25 14:09:26
Message-ID: 20080625140926.GA17243@depesz.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Wed, Jun 25, 2008 at 09:50:18AM -0400, Mark Stosberg wrote:
> hits
> hit_id
> partner_id
>
> views
> view_id
> partner_id
>
> There is of course a "partners" table with a "partner_id" column.
>
> My target result is more like
>
> partner_id
> total_views
> total_hits

select
coalesce(h.partner_id, v.partner_id) as partner_id,
coalesce(v.count, 0) as total_views,
coalesce(h.count, 0) as total_hits
from
(select partner_id, count(*) from hits group by partner_id) as h
full outer join
(select partner_id, count(*) from views group by partner_id) as v
on h.partner_id = v.partner_id
;

depesz

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Mark Stosberg 2008-06-25 14:17:55 Re: GROUP BY on a column which might exist in one of two tables
Previous Message Mark Stosberg 2008-06-25 13:50:18 GROUP BY on a column which might exist in one of two tables