Re: Count

From: Bricklen Anderson <banderson(at)presinet(dot)com>
To: Bob Pawley <rjpawley(at)shaw(dot)ca>
Cc: PostgreSQL <pgsql-general(at)postgresql(dot)org>
Subject: Re: Count
Date: 2008-01-23 19:22:37
Message-ID: 479793FD.2000103@presinet.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Bob Pawley wrote:
> I have a table with four columns that will either be null or hold the
> value 'true'.
>
> I want to obtain the count of these columns, within a particular row,
> that have 'true' as a value (0 to 4).
>
> I have attempted the Select count method but it seems that I need
> something more.
>
> If anyone has any thoughts it would be much appreciated.
>
> Bob

Something like this?

create table t (id int, w bool, x bool, y bool, z bool);
insert into t values
(1,null,null,'t','t'),
(1,null,'t','t',null),
(2,'t',null,'t',null),
(2,'t',null,'t',null),
(3,null,'t','t','t'),
(4,'t','t','t','t');

select id,
sum(case when w is null then 0 else 1 end) as w,
sum(case when x is null then 0 else 1 end) as x,
sum(case when y is null then 0 else 1 end) as y,
sum(case when z is null then 0 else 1 end) as z
from t
group by id
order by id;

id | w | x | y | z
----+---+---+---+---
1 | 0 | 1 | 2 | 1
2 | 2 | 0 | 2 | 0
3 | 0 | 1 | 1 | 1
4 | 1 | 1 | 1 | 1

?

In response to

  • Count at 2008-01-23 18:50:48 from Bob Pawley

Browse pgsql-general by date

  From Date Subject
Next Message Tom Hart 2008-01-23 19:54:14 ascii to utf-8
Previous Message Rick Schumeyer 2008-01-23 19:10:09 Re: Tips for upgrading from 7.4