1

How can I get the value of "profit" to be returned by MySQL. totalCost and totalSell are obtained from the database.

select 
  sum(cost) as totalCost
  , sum(sell) as totalSell
  , (totalSell-totalCost) as profit 
from orders

3 Answers 3

4

Why don't you try to directly count profit instead of using aliases?

Try this:

Select SUM(cost) AS totalCost
     , SUM(sell) AS totalSell
     , (SUM(sell) - SUM(cost)) AS profit
FROM orders

See this SQLFiddle

Sign up to request clarification or add additional context in comments.

Comments

1

Dont perform, operations on aliases. You need to change (totalSell-totalCost) to (sum(cost)-sum(sell))

 Select sum(cost) as totalCost  , sum(sell) as totalSell, (sum(cost)-sum(sell)) as profit
     from orders

Comments

1

You can't use aliases in the select portion of the query that is declaring them:

select sum(cost) as totalCost, 
       sum(sell) as totalSell, 
       sum(sell) - sum(cost) as profit
from orders

If you wanted to do this using an alias (for some reason), you can do so when defining them in a subquery:

select *, totalCost - totalSell as profit
from ( select sum(cost) as totalCost, 
              sum(sell) as totalSell, 
       from orders ) t

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.