I have a question which has 3 tables:
1.Review(JobID)
2.Job(BusinessNumber)
3.Business(BusinessNumber) (Foreign Keys).
I need to retrieve data and create table which has 4 columns HighestBusiness
, HighestRating
, LowestBusiness
, Lowest Rating
.
select business.businessname AS HIGHESTRATEDBUSINESS,
max(review.reviewrating) as HIGHEST
from business
inner join job
on job.selectedbusinessabnnumber=business.abnnumber
inner join review
on review.jobid=job.jobid
where review.reviewrating = (select max(reviewrating)
from review)
GROUP BY businessname
UNION
select business.businessname AS LOWESTRATEDBUSINESS,
MIN(review.reviewrating) as HIGHEST
from business
inner join job
on job.selectedbusinessabnnumber=business.abnnumber
inner join review
on review.jobid=job.jobid
where review.reviewrating = (select MIN(reviewrating)
from review)
GROUP BY businessname
/
I didn't create table as of now, I just wanted the four columns to be shown.
The UNION operator produces one result set from two sets with the same projection. What you need is a new projection of four columns. So turn the two sub-queries into inline views and use a CROSS JOIN:
select h.highestratedbusiness
, h.highest
, l.lowestratedbusiness
, l.lowest
from
(select business.businessname AS HIGHESTRATEDBUSINESS,
max(review.reviewrating) as HIGHEST
from business
inner join job
on job.selectedbusinessabnnumber=business.abnnumber
inner join review
on review.jobid=job.jobid
where review.reviewrating = (select max(reviewrating)
from review)
GROUP BY businessname ) h
cross join
(select business.businessname AS LOWESTRATEDBUSINESS,
MIN(review.reviewrating) as HIGHEST
from business
inner join job
on job.selectedbusinessabnnumber=business.abnnumber
inner join review
on review.jobid=job.jobid
where review.reviewrating = (select MIN(reviewrating)
from review)
GROUP BY businessname ) l
/
A CROSS JOIN produces one record for each combination of records in the joined sets. This will be fine when the data produces one highest rated business and one lowest rated business. But it will generate a Cartesian product if there's a tie in either or both places. There are ways around that, so please refine your question if that is a roadblock for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.