0

I have 2 columns from a table and i want to add a third column to output the result of a calculation

select statement at the moment is:

select revenue, cost
from   costdata

my 2 columns are revenue and cost

table name: costdata

my formula is: = ((revenue - cost)/ revenue)*100

I want the third column to be named 'result'

any idea on how to do this in a select statement?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
jeffry
  • 327
  • 2
  • 8
  • 23

4 Answers4

2
SELECT revenue
     , cost
     , ((revenue - cost) / revenue) * 100 As result
FROM   costdata

You mentioned in the comments that you get a divide by zero error. This wll occur when revenue equals zero.

What you want to happen in this scenario is up to you but this should get you started

SELECT revenue
     , cost
     , CASE WHEN revenue = 0 THEN
         0
       ELSE
         ((revenue - cost) / revenue) * 100
       END As result 
FROM   costdata
gvee
  • 16,732
  • 35
  • 50
1

Try,

select revenue, cost,((revenue - cost)/ revenue)*100 AS result
from   costdata
BAdmin
  • 927
  • 1
  • 11
  • 19
  • I think your 'revenue' returning 0 in some cases. You have to check that. – BAdmin Feb 06 '14 at 13:39
  • You can use Select dividend / nullif(divisor, 0) source: http://stackoverflow.com/questions/861778/how-to-avoid-the-divide-by-zero-error-in-sql – BAdmin Feb 06 '14 at 13:42
1
SELECT revenue, cost, ((revenue - cost)/ revenue)*100 AS result FROM costdata
Prahalad Gaggar
  • 11,389
  • 16
  • 53
  • 71
1

Query:

SELECT revenue, 
       cost,
       CASE WHEN revenue <> 0 
            THEN ((revenue - cost) / revenue) * 100
       ELSE 0 END As result
FROM   costdata
Justin
  • 9,634
  • 6
  • 35
  • 47