First of all. Sorry for the vague title. I couldn't figure out how to frame it. With the sample code, I hope you can understand my doubt.
The task was to find out the top three facilities in a club in terms of revenue generated. I thought this is the final code.
SELECT x,y as rank
FROM tableA
where rank <=3;
But this says the rank column doesn't exist. So I have to include this in another subquery to filter the top 3 ranks.
SELECT x,rank
FROM
(SELECT x,y as rank
FROM tableA
) as sub
where rank<=3;
Why? I need one extra subquery? Why can't it filter using where clause in the original query?
Code for Facility names, and their rank by revenue:
select res.name,rank() over(order by total desc) as rank
from
(select fac.facid,fac.name,sum(slots*
case
when memid=0 then guestcost
else membercost
end) as total
from cd.bookings bks
inner join cd.facilities fac
on bks.facid=fac.facid
group by fac.facid
order by total desc) as res
What I thought would work:
select res.name,rank() over(order by total desc) as rank
from
(select fac.facid,fac.name,sum(slots*
case
when memid=0 then guestcost
else membercost
end) as total
from cd.bookings bks
inner join cd.facilities fac
on bks.facid=fac.facid
group by fac.facid
order by total desc) as res
where rank<=3;
(why this don't work??)
What works :
select name, rank
from
(select res.name,rank() over(order by total desc) as rank
from
(select fac.facid,fac.name,sum(slots*
case
when memid=0 then guestcost
else membercost
end) as total
from cd.bookings bks
inner join cd.facilities fac
on bks.facid=fac.facid
group by fac.facid
order by total desc) as res) as sub
where rank <=3;