Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

When I run the following query

select distinct A.movieID, A.avgStars from 
(select mID as movieID, avg(stars) as avgStars
from Rating
group by mID) A
where  A.avgStars <= all(select A.avgStars from A);

I get the error "Invalid object name 'A'."

Do you know why I'm getting this?

Thanks!

share|improve this question
    
Thank you @SqlZim and others! – bst-for-life 2 hours ago

You can't reference an alias from a subquery at the same scope. You can do this with a CTE, though; perhaps you meant:

;WITH Avgs AS
(
  select mID as movieID, avg(stars) as avgStars
  from Rating group by mID
)
SELECT movieID, avgStars FROM Avgs
WHERE avgStars <= ALL (SELECT AvgStars FROM Avgs);

You shouldn't need DISTINCT there, either.

share|improve this answer

You're trying to reference the alias in your from statement in a new subquery.

You could do something like that with a common table expression though.

;with a as (
select mID as movieID, avg(stars) as avgStars
  from Rating
  group by mID
)

select distinct A.movieID, A.avgStars 
from a
where  A.avgStars <= all(select A.avgStars from A);
share|improve this answer

The is failing because your Where clause. The all(select A.avgStars from A) cannot see the "A" table aliased above in this context. It thinks you're trying to link to a table named A.

share|improve this answer

The other answers have already identified the problem and how to solve it.

Here is another way, that simplifies the query further:

select top (1) with ties
    mID as movieID, avg(stars) as avgStars
from Rating 
group by mID
order by avgStars ;
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.