I am performing a SQL query in PostgreSQL using a CASE
statement like this:
SELECT
CASE column1
WHEN something THEN 10
ELSE 20
END AS newcol1
CASE column12
WHEN something THEN 30
ELSE 40
END AS newcol2
COUNT(column3) newcol3
FROM table
GROUP BY newcol1,newcol2,newcol3
I need a fourth column which has to be the result of newcol2 * newcol3
, how can I do that?
If I put (newcol2 * newcol3) AS newcol4
I get a syntax error.
A CTE is a valid approach, giving additional options.
For a simple case like this a plain subquery is simpler and slightly faster.
BTW: I removed
newcol3
fromGROUP BY
, since you are running the aggregate functioncount()
on it, which is slightly nonsensical.You can always use a CTE to abstract things away to a different level, if that helps - something along the lines of ...