Skip to content
Advertisement

Postgres where clause over two columns from subquery

  • Database: Postgres
  • Table name: records
  • Has 4 columns Year | Dept | Expense | Month

So per year there can be up to one record for each month / per department.

I have a sub-query which returns me the below data based on constraints.

Now I need to run another query on the same table to get a total of the expenses for each value pair.

Using the output of the subquery, my main query will be something like

When I run this select statement, the output returned is only containing data for TECH across all three years.

Please can help understand how I can run the main select over all the rows of the subquery

Advertisement

Answer

Refactor the subquery to a join.

Say you have

which won’t work. You rewrite to

Note, in PostgreSQL you shouldn’t use a CTE (WITH query) for this.

You can abbreviate

to

though.

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