I'm trying to create a simple pivot-like report, which I managed to do with SQL Server's pivot
, but now the SQL needs to run on SQL Server and Postgresql.
So, I've changed the SQL to use CASE
like this:
SELECT SPACENAME
, CASE WHEN PERMTYPE='VIEWSPACE' THEN 'X' END AS "Read Access"
, CASE WHEN PERMTYPE='EDITSPACE' THEN 'X' END AS "Write Access"
FROM ( ...) sub
GROUP BY SPACENAME, PERMTYPE
ORDER BY SPACENAME
The "..." is where a complex subquery goes, the output of which is:
SPACENAME PERMTYPE
Testware Releases EDITSPACE
Testware Releases VIEWSPACE
Documentation VIEWSPACE
I'm trying to get a report like:
SPACENAME Read Access Write Access
Testware Releases X X
Documentation X
But instead I'm getting:
SPACENAME Read Access Write Access
Testware Releases X
Testware Releases X
Documentation X
I built my CASE
upon another example here: PostgreSQL crosstab() alternative with CASE and aggregates)
There are only 2 differences:
- The other answer only puts one column in the
GROUP BY
. I agree that this is what makes sense, but when I do that I get an error: Column 'sub.PERMTYPE' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. - The other answer uses a
sum()
inside theCASE
. If I do this (along with the single column inGROUP BY
), I can get it work, but it shows a numeric-based report, but I really just want the "X" in the right column...
Is there any way to get the X's in the columns instead of a number?