Skip to content
Advertisement

How to do an arithmetic operation with aliased column in SQL

I have a databse table as like below:

Here, received_by and sent_by are two user ID those who are receiving and sending the product respectively. I want to calculate the total amount of each product of a single user by subtracting the sent amount from received amount. My current query looks like below:

Here I get an error that Unknown column 'received' in 'field list'.

How can I calculate each users inventory/stock?

Advertisement

Answer

You can’t use the calculated columns in the SELECT list.
Also you need the aggregate function SUM().

One way to do it is with a subquery:

Or:

See the demo.

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