Re: Q: using generate_series to fill in the blanks

From: Sam Mason <sam(at)samason(dot)me(dot)uk>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: Q: using generate_series to fill in the blanks
Date: 2007-12-07 12:05:22
Message-ID: 20071207120522.GN1955@frubble.xen.chris-lamb.co.uk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Fri, Dec 07, 2007 at 01:18:13PM +0800, Ow Mun Heng wrote:
> select i.i as vdt,dcm_evaluation_code as c_id
> , case when count(vdt_format) = 0 then NULL else count(vdt_format) end
> as count
> from generate_series(1,7) i
> left join footable f
> on i.i = f.vdt_format
> and c_id in ('71','48')
> group by c_id, i.i
> order by c_id,i.i;
>
> When Joined into 1 query
> vdt | c_id | count
> -----+-------+-------
> 1 | HMK71 | 533
> 2 | HMK71 | 30
> 3 | HMK71 | 15
> 4 | HMK71 | 10
> 5 | HMK71 | 12
> 6 | HMK71 | 15 << What happened to 7?
> 1 | HML48 | 217
> 2 | HML48 | 86
> 3 | HML48 | 46
> 4 | HML48 | 50
> 5 | HML48 | 4
> 7 | |

You need to start by generating all of the values you consider you
want. In the previous example this was easy as all you wanted was a
set of numbers. Now you want the cartesian product of this series and
something else. So you need to be doing something like:

SELECT x.i, x.j, COUNT(t.k)
FROM (SELECT DISTINCT t.i,s.j FROM table t, generate_series(1,7) s(j)) x
LEFT JOIN table t ON (x.i,x.j) = (t.i,t.j)
GROUP BY x.i, x.j
ORDER BY x.i, x.j;

Sam

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Ted Byers 2007-12-07 14:29:08 Re: SQL design pattern for a delta trigger?
Previous Message Alvaro Herrera 2007-12-07 11:56:01 Re: Nested loop in simple query taking long time