Re: Counting boolean values (how many true, how many false)

From: maarten <maarten(dot)foque(at)edchq(dot)com>
To: Alexander Farber <alexander(dot)farber(at)gmail(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Counting boolean values (how many true, how many false)
Date: 2010-11-16 16:49:31
Message-ID: 1289926171.4363.81.camel@localhost
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hi,

sum doesn't like booleans, but it does like integers so:
sum(boolval::int) solves that problem for you.

SELECT id,sum(good::int + fair::int + nice::int) would get you a total
of the three for each row

good luck,
Maarten

On Tue, 2010-11-16 at 17:23 +0100, Alexander Farber wrote:
> Hello,
>
> if I have this table with 3 boolean columns:
>
> # \d pref_rate
> Table "public.pref_rep"
> Column | Type | Modifiers
> ------------+-----------------------------+---------------
> id | character varying(32) |
> author | character varying(32) |
> good | boolean |
> fair | boolean |
> nice | boolean |
> about | character varying(256) |
> last_rated | timestamp without time zone | default now()
> Foreign-key constraints:
> "pref_rate_author_fkey" FOREIGN KEY (author) REFERENCES pref_users(id)
> "pref_rate_id_fkey" FOREIGN KEY (id) REFERENCES pref_users(id)
>
> - how can I please count the number of
> true's and false's for each column for a certain id?
> (to find that persons rating)
>
> I'm trying:
>
> select sum(fair=true), sum(fair=false) from pref_rep;
>
> but sum() doesn't like a boolean as an argument.
>
> I've only come up with
>
> select count(*) from pref_rep where fair=true and id='XXX';
>
> but this would mean I have to call this line 6 times? (2 x column).
>
> Thank you
> Alex
>

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Thom Brown 2010-11-16 17:02:32 Re: Counting boolean values (how many true, how many false)
Previous Message Gary Fu 2010-11-16 16:45:29 Re: escape character for 'psql -c ' command