Skip to content
Advertisement

PostgreSQL – Subtraction based on column data simplifying query

I’m trying to subtract data from the table based on another column which represent their category.

For example:

I want to subtract the amount of Glass with the amount of Meat and Fish

I am able to write a simple query to subtract the data with one another but I was wondering if there was a way of simplifying the query.

The codes I have written:

Advertisement

Answer

You can just use conditional aggregation:

Strictly speaking the where clause is not necessary, but if you have a lot of values of z it can make the query more performant.

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