Question

Newbie to sql here. I am trying to select only tuples whose values in one column are larger than the average of that column. The problem is, the relation I am working with is created in the FROM clause, because I need to add a transformation (and also take a subset).

I was originally using a WHERE clause, but this SO answer led me to believe that I could fix the problem by using a HAVING clause instead. I am still receiving this error, however:

Table 'msan692db.l' doesn't exist

How can I make the necessary comparison in a way that is not blind to the alias I created in my FROM clause? I think I could just explicitly recreate the needed relation in the WHERE/HAVING clause, but I will be adding more later and this seems terribly inefficient.

This is my code as it stands:

select *
from 
    (select *, ascii(substring(CREDIT_Grade,1,1)) + cast(substring(CREDIT_Grade,2,1) as unsigned) * .2 as CREDIT_Grade_num
    from loanstats
    where Loan_duration = 36) L
group by loan_ID
having
    Interest_Rate > (select avg(Interest_Rate) from L)

EDIT: I have confirmed, by the way, that the FROM clause by itself returns a valid relation.

Was it helpful?

Solution

Can't you move the subquery in the FROM section? Like this?

select *
from 
    (select *, ascii(substring(CREDIT_Grade,1,1)) + cast(substring(CREDIT_Grade,2,1) as unsigned) * .2 as CREDIT_Grade_num
    from loanstats
    where Loan_duration = 36) L,
    (select avg(Interest_Rate) avg_rate from L_COPY_HERE) iRateAvg
group by loan_ID
having
    Interest_Rate > iRateAvg.avg_rate  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top