I’m trying to count multiple values in multiple coluns in a table and I did that:
TABLE
id | risk | record | api |
---|---|---|---|
1 | OK | OK | NO |
2 | OK | OK | OK |
3 | OK | OK | OK |
4 | OK | NO | OK |
5 | NO | OK | NO |
SQL:
select 'risk' as nm_test, risk as tst_result, count(*) as qty
from table
group by risk
union
select 'record' as nm_test, record as tst_result, count(*) as qty
from table
group by record
union
select 'api' as nm_test, api as tst_result, count(*) as qty
from table
group by api
The result is the following table:
nm_test | tst_result | qty |
---|---|---|
risk | OK | 4 |
risk | NO | 1 |
record | OK | 4 |
record | NO | 1 |
api | OK | 3 |
api | NO | 2 |
But, instead, I would like to have the result table pivoted like this:
nm_test | OK | NO |
---|---|---|
risk | 4 | 1 |
record | 4 | 1 |
api | 3 | 2 |
I tried to do that, but I was unable to figure out the trick! Any help would be valuable.
Cheers.
3
Answers
If you have a fixed columns to pivot, and values are ‘OK’ and ‘NO’ only then :
Demo here
Try this:
Forget using
UNION
.Pivoting from columns to rows in PostgreSQL can be done by casting into and out of
jsonb
. This helps if you will be adding more tests in the future.Using
- id
gets rid of that column from the results.Using
filter
on the aggregates pivots back to columns. This is useful so long as the possible results are finite and known.Working example.