2
SELECT 
if('1000'>plan_limit_max,'1000'-plan_limit_max,0) as 'Overage',
if(`per_hour_cost`='0', `per_period_cost`+'10'*`Overage`, per_hour_cost*720) AS 'Total'

FROM `service_price`

order by Total asc
;

There is an error with Overage at line 3

Error Code: 1054. Unknown column 'Overage' in 'field list'

Is there a way to do what I want with one query? I want to order results by total price, but to calculate it I have to calculate the usage exceeds the limit.

I know there should be other ways to do it, use more than one queries, create views, etc.. I just wonder if there is a simpler query for this.

2
  • Can you post the error as well? Commented Oct 17, 2011 at 3:34
  • 1
    Why are you single-quoting what look like numeric constants (e.g., '1000') ? Commented Oct 17, 2011 at 3:48

3 Answers 3

1

You can compute Overage once, in a subquery:

SELECT Overage,
       IF(per_hour_cost = 0, per_period_cost + 10 * Overage, per_hour_cost * 720)
         AS Total
  FROM (SELECT IF(1000 > plan_limit_max, 1000 - plan_limit_max, 0) AS Overage,
               service_price.*
          FROM service_price) d;
Sign up to request clarification or add additional context in comments.

Comments

1

Overage is not defined as part of the query, only as the column header in the result. You cannot reference that column as it does not yet exist... You've got to use something like the SQL below:

SELECT 
if('1000'>plan_limit_max,'1000'-plan_limit_max,0) as 'Overage',
if(`per_hour_cost`='0', `per_period_cost`+'10'*if('1000'>plan_limit_max,'1000'-             plan_limit_max,0), 
per_hour_cost*720) AS 'Total'

FROM `service_price`

order by Total asc

Comments

0

You have an error putting " `` " in OVERAGE. You must use ' ' in OVERAGE.

SELECT 
if('1000'>plan_limit_max,'1000'-plan_limit_max,0) as 'Overage',
if(`per_hour_cost`='0', `per_period_cost`+'10'* 'Overage', per_hour_cost*720) AS 'Total'

FROM `service_price`

order by Total asc
;

1 Comment

No, that will force string interpretation of the token Overage. MySQL will summarily truncate that to a zero and will issue a warning something like: Truncated incorrect DOUBLE value: 'Overage'

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.