1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 23:28:02 +00:00

Add Count The Number Of Trues In An Aggregate Query as a postgres til

This commit is contained in:
jbranchaud
2019-10-17 21:22:58 -05:00
parent 8173781406
commit 1d118363b9
2 changed files with 28 additions and 1 deletions

View File

@@ -0,0 +1,26 @@
# Count The Number Of Trues In An Aggregate Query
The `sum` function is an aggregate function that allows you to sum up a bunch
of integers. What if you want to sum up a boolean column? You may want to know
how many times `true` appears in a collection of grouped records.
This can be done by mixing in a `case` statement.
```sql
select
author_id,
sum(case when available then 1 else 0 end)
from books
group by author_id;
```
Here, we are able to find out for each author how many books they have
available.
If we want to count `false` values, we can just invert the `sum` statement:
```sql
sum(case when available then 0 else 1 end)
```
[source](https://stackoverflow.com/a/5396728/535590)