From: | Richard Huxton <dev(at)archonet(dot)com> |
---|---|
To: | Wei Weng <wweng(at)kencast(dot)com> |
Cc: | pgsql-sql(at)postgresql(dot)org |
Subject: | Re: How do I optimize this? |
Date: | 2009-03-18 08:35:13 |
Message-ID: | 49C0B241.6030005@archonet.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-sql |
Wei Weng wrote:
> I made a mistake in the queries:
>
> They should be
>
> update T set t1 = b.aa FROM (select COUNT(1) as aa FROM D WHERE D.da =
> 1) as b where tkey = <value>;
> update T set t2 = b.aa FROM (select COUNT(1) as aa FROM D WHERE D.da =
> 2) as b where tkey = <value>;
> ...
> update T set t10 = b.aa FROM (select COUNT(1) as aa FROM D WHERE D.da =
> 10) as b where tkey = <value>;
You should be able to generate all the counts from one scan:
UPDATE T set t1 = b.a1, t2 = b.a2 ...
FROM (
SELECT
sum(CASE WHEN D.da=1 THEN 1 ELSE 0 END) AS a1,
sum(CASE WHEN D.da=2 THEN 1 ELSE 0 END) AS a2,
...
FROM D
) AS b
WHERE tkey = <value>
You might also want to look at the crosstab functions in the tablefunc
contrib module (see appendix F of the manuals).
--
Richard Huxton
Archonet Ltd
From | Date | Subject | |
---|---|---|---|
Next Message | Srikanth | 2009-03-18 16:02:29 | Re: SQL to Check whether "AN HOUR PERIOD" is between start and end timestamps |
Previous Message | Ivan Sergio Borgonovo | 2009-03-18 08:16:23 | 2 left join taking in too many records, 1 join and 1 left join too few was: join |