3

I have this query:

select qa_returns_items.item_code, 
               (CASE status_code
                 WHEN 11 THEN (qa_returns_items.item_quantity - qa_returns_residues.item_quantity) 
                 WHEN 12 THEN (qa_returns_items.item_quantity + qa_returns_residues.item_quantity)   END) as total_ecuation , 
                qa_returns_residues.item_unitprice,
               ( qa_returns_residues.item_unitprice * total_ecuation) as item_subtotal,
               (qa_returns_residues.item_discount * item_quantity) as item_discount,
               ( ( qa_returns_residues.item_unitprice * total_ecuation) -   
                 (qa_returns_residues.item_discount * item_quantity) ) as item_total
from qa_returns_residues, qa_returns_items
where
    total_ecuation > 0 
AND qa_returns_items.item_code = qa_returns_residues.item_code;

It shows me the error: Unknown column 'total_ecuation' in 'field list'

how I can use the alias as a column?

2 Answers 2

3

Consider using a subquery. I've added table aliases to make the query more readable:

select  *
,       item_unitprice * total_ecuation as item_subtotal
,       (item_unitprice * total_ecuation) - item_discount as item_total
from    (
        select  ri.item_code
        ,       case status_code
                when 11 then ri.item_quantity - rr.item_quantity 
                when 12 then ri.item_quantity + rr.item_quantity
                end as total_ecuation
        ,       rr.item_unitprice
        ,       rr.item_quantity
        ,       rr.item_discount * rr.item_quantity as item_discount
        from    qa_returns_residues rr
        join    qa_returns_items ri
        on      ri.item_code = rr.item_code
        ) as SubQueryAlias
where   total_ecuation > 0
Sign up to request clarification or add additional context in comments.

6 Comments

You forgot to add that you also replaced the comma join with an explicit join (to make the query more readable, of course). :)
Corrected syntax errors but I always get the same error. Unknown column 'total_ecuation' in 'field list'
Aha, total_equation was used in other columns as well. I edited the answer to move those calculations to the outer query, does that help?
The syntax is right now, but i get another error: Unknown column 'rr.item_unitprice' in 'field list'
In the outer query it should be either SubQueryAlias.item_unitprice or item_unitprice, edited in answer.
|
2

I'm afraid you have to rewrite your query to use a named subquery, or repeat the whole case statement in the where clause...

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.