Mohideen bin Mohammed
Mohideen bin Mohammed

Reputation: 20186

MySQL calculate difference between derived column of same query

How to calculate the difference between derived fields of the same query?

Here is my SQL query:

select Empname, sum(monthly_net) as Net,
sum(monthly_gross) as Gross, 
(Net-Gross) as diff_amount * from emp_table;

Here I derive fields called Net and Gross, and I want the difference between those. Is that possible to calculate the difference between derived fields?

Upvotes: 0

Views: 106

Answers (2)

Jay Shankar Gupta
Jay Shankar Gupta

Reputation: 6088

you can't use aliases in the same query and also put * in front of all other column you can't use * after any other * must be the first in Select as below:

SELECT *,
       Empname, 
       sum(monthly_net) as Net,
       sum(monthly_gross) as Gross, 
       sum(monthly_net)-sum(monthly_gross) as diff_amount
FROM emp_table;

Upvotes: 1

Nick
Nick

Reputation: 147206

Not directly (you can't use aliases in the same query), but you could use

sum(monthly_net)-sum(monthly_gross) as diff_amount

Upvotes: 1

Related Questions