SELECT question_id, COUNT(*) FROM Ansers_Boolean WHERE value=TRUEGROUP 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=TRUEGROUP BY question_id
UNION ALL
SELECT question_id, 0 FROM Answers_Boolean AS AB0 WHERE NOT EXISTS (SELECT * FROM
Answers_BooleanAS 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
>