From: Joel Burton <joel@joelburton.com>
To: Dan MacNeil <dan@ltc.org>
To: pgsql-sql <pgsql-sql@postgresql.org>
Subject: Re: count(boolean)
Date: Sun, 19 May 2002 10:58:16 -0400
Message-ID: <JGEPJNMCKODMDHGOBKDNMELMCOAA.joel@joelburton.com> (raw)
In-Reply-To: <001d01c1ff3f$d7d86470$b11a9318@prometheus>
SELECT question_id,
COUNT(*)
FROM Ansers_Boolean
WHERE value=TRUE
GROUP BY question_id;
sort of works; it's fast & correct, but if a question has no true responses,
it leaves off that question. This may or may not be acceptable to you.
You could fix that with:
SELECT question_id,
COUNT(*)
FROM Answers_Boolean
WHERE value=TRUE
GROUP BY question_id
UNION ALL
SELECT question_id,
0
FROM Answers_Boolean AS AB0
WHERE NOT EXISTS (SELECT *
FROM Answers_Boolean AS AB1
WHERE AB0.question_id = AB1.question_id
AND value = TRUE);
But it performs slowly. I normally create turn the bools into 1 or 0 and add
them up (called a "Characteristic function"):
SELECT question_id,
SUM(CASE value WHEN TRUE THEN 1 ELSE 0 END) AS num_true
FROM Answers_Boolean
GROUP BY question_id;
Plus, it's easy this way to add a num_false column, by just copying
num_true.
Joel BURTON | joel@joelburton.com | joelburton.com | aim: wjoelburton
Knowledge Management & Technology Consultant
> -----Original Message-----
> From: pgsql-sql-owner@postgresql.org
> [mailto:pgsql-sql-owner@postgresql.org]On Behalf Of Dan MacNeil
> Sent: Sunday, May 19, 2002 10:17 AM
> To: pgsql-sql
> Subject: [SQL] count(boolean)
>
>
> I have a table answers_boolean:
>
> question_id | integer | not null
> evaluation_id | integer | not null
> value | boolean |
>
> I'd like output in the form:
>
> question_id, count_true, count_false
>
> ....where count_true is the number of questions answered "true"
>
> SELECT
> question_id AS id, value AS val , count(value) AS cnt
> FROM
> answers_boolean
> GROUP BY
> question_id,value;
>
> gives me:
> id | val | cnt
> ----+-----+-----
> 2 | f | 3
> 2 | t | 3
> 3 | f | 2
> 3 | t | 4
>
> ...which is sorta what I want.
>
> I've looked through the docs & archive but haven't found the answer.
>
> TIA
>
> ---------------------------(end of broadcast)---------------------------
> TIP 3: if posting/reading through Usenet, please send an appropriate
> subscribe-nomail command to majordomo@postgresql.org so that your
> message can get through to the mailing list cleanly
>
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: pgsql-sql@postgresql.org
Cc: joel@joelburton.com, dan@ltc.org
Subject: Re: count(boolean)
In-Reply-To: <JGEPJNMCKODMDHGOBKDNMELMCOAA.joel@joelburton.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox