Skip to content
Advertisement

How to select count of 0s, 1s, and both 0s and 1s in a postgres table column?

Say there’s a table that has columns named binary_value, name, and created_at along with the id column.

Here’s the SQL Fiddle for this question: http://sqlfiddle.com/#!15/d15d1/36

What would be an efficient query to get a result like the following?

So far, I’ve got:

Which gives it in column form:

How can we get the result in a row? Perhaps there’s a different approach altogether than Common Table Expression? I’m starting to look at crosstab, which is postgres-specific, and so wondering if all this is overkill.

Including DDL and data here, too:

Advertisement

Answer

I think you just want conditional aggregation:

The date comparison looks rather, uh, specific. I assume that you really intend a range there.

Here is a SQL Fiddle.

Note: If you are really using Postgres 9.3, then you can’t use the filter clause (alas). Instead:

Also, if you wanted the results in three separate rows, a simpler query is:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement