Skip to content
Advertisement

reuse of subqueries with different WHERE clause

I have a query which I looks schematically like this

I want to reuse the subqueries in sub_one, sub_two, sub_all because they are almost identical with the exception of type in SELECT and the WHERE condition.

How can I avoid copy-pasting these subqueries?

Advertisement

Answer

Use GROUP BY:

In Postgres, I would further simplify this. You could use FILTER or summing binary values:

I would also dispense with the CTE and just put the logic in the outer query directly, but that is more a matter of style.

EDIT:

You can use another CTE:

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