I have this table on a postgres db (proofs). proof_1, proof_2 and proof_3 are boolean columns indicating whether the user (user_id) has submitted the proofs:
| user_id | proof_1 | proof_2 | proof_3 |
|---|---|---|---|
| 1 | true | true | false |
| 2 | true | false | false |
| 3 | true | true | true |
I need to count how many proofs are submitted by each user. This is the query that I came up:
> select
user_id,
length(
concat(
case when proof_1 then '1' end,
case when proof_2 then '1' end,
case when proof_3 then '1' end)
)) as proof_counts
from
proofs
The query above would work. But I don't think that it is the best query to do. Please advice on what query should be done?
proof_1::int + proof_2::int + proof_3::int. If you want something that can handle a variable number ofproof_Xcolumns, please say so as that can be done usingto_jsonb()andjsonb_each()to pivot columns to rows.