Re: Random via Subselect or Temporary Table

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: tom(at)minnesota(dot)com
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Random via Subselect or Temporary Table
Date: 2003-08-09 03:17:31
Message-ID: 3014.1060399051@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

"Thomas T. Thai" <tom(at)minnesota(dot)com> writes:
> CREATE TEMPORARY TABLE t1 AS SELECT catnum, title, random() AS r FROM
> randtest;
> CREATE TEMPORARY TABLE t2 AS SELECT catnum, max(r) AS mr FROM t1 GROUP BY
> catnum;
> SELECT t1.catnum, t1.title, t1.r FROM t1, t2 WHERE t1.catnum = t2.catnum
> AND t1.r = t2.mr;

> The results seem pretty random per group. Is there a better way of
> accomplishing this task without using temporary tables? Maybe with
> subselects?

I'd suggest using DISTINCT ON (catnum) with ORDER BY catnum, random().
See the SELECT reference page's "weather reports" example for
background.

regards, tom lane

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2003-08-09 03:29:42 Re: 7.3.3 behaving differently on OS X 10.2.6 and FreeBSD
Previous Message Tom Lane 2003-08-09 03:13:28 Re: remove $ from money field