Re: CASE

From: Rod Taylor <rbt(at)rbt(dot)ca>
To: jtx(at)hatesville(dot)com
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: CASE
Date: 2003-05-19 23:24:49
Message-ID: 1053386689.24151.49.camel@jester
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Mon, 2003-05-19 at 02:59, James Taylor wrote:
> Hi everyone, I'm trying to figure out how to get CASE working in a sum
> aggregate function. Pretty simple query:
>
> select sum(numbers) from lists where uid=1;
>
> It's possible that there may be 0 rows where uid == 1. Instead of
> returning 1 blank row, I want it to return '0'. So, I tried this:
>
> select case(sum(numbers)) when null then 0 else sum(numbers) end from
> list_results;

Use Coalesce:

SELECT coalesce(sum(numbers), 0) FROM lists WHERE uid = 1;

To use case, efficiently, if you really want:

SELECT CASE WHEN sum_numbers IS NULL THEN 0
ELSE sum_numbers
END AS sum_numbers
FROM (SELECT sum(numbers) AS sum_numbers
FROM lists
WHERE uid = 1
) as tab;

--
Rod Taylor <rbt(at)rbt(dot)ca>

PGP Key: http://www.rbt.ca/rbtpub.asc

In response to

  • CASE at 2003-05-19 06:59:46 from James Taylor

Browse pgsql-sql by date

  From Date Subject
Next Message Manfred Koizar 2003-05-19 23:52:41 Re: CASE
Previous Message David W Noon 2003-05-19 23:19:32 Re: Performance on temp table inserts