tags:

views:

49

answers:

2

I have the following table:

id  |  kwh  |   cost
---------------------
 1  |  10   |   8.95
 2  |  20   |    0
 3  |  100  |  16.54

I need to get the average cost.

If the cost is still the default (0), the cost value is calculated with the following formula: (7.87 + (kwh * 8.19)/100) * 1.03

So id 2's cost will be estimated at 9.79 for an average cost of 35.28/3 = 11.76.

Is there a mySQL query that will calculate the cost if the column has the default value and use inputed value otherwise?

+1  A: 

You can use a CASE expression to test whether the cost is 0:

SELECT
  *,
  CASE cost WHEN 0 THEN (7.87 + (kwh * 8.19) / 100) * 1.03 ELSE cost END calc_cost
FROM
  tablename

You can then use this expression with AVG to get the average:

SELECT
  AVG(CASE cost WHEN 0 THEN (7.87 + (kwh * 8.19) / 100) * 1.03 ELSE cost END)
FROM
  tablename
Phil Ross
+1  A: 

Try this:

select 
    case
        when cost = 0 then (7.87 + (kwh * 8.19) / 100) * 1.03
        else cost
    end as calculated_cost
from table
where id = 2

[edit] Ah, you need the average!

select 
    avg(case
        when cost = 0 then (7.87 + (kwh * 8.19) / 100) * 1.03
        else cost
    end as calculated_cost)
from table
Tamás Mezei