简体   繁体   中英

SQL (Oracle 12c): How to select results from another select statement (nesting?/sub--query?)

I'm working on a homework problem for an intro SQL class that I'm taking. This week's topic is Summary Functions. Here is the problem:

Here bellow are the pictures of the relevant tables:

在此处输入图片说明

在此处输入图片说明

I've written this query which returns the average retail price by publisher name and category, but cannot figure out how to return just the average retail that is over $50.

select p.name, b. category, avg(b.retail)
from books b, publisher p 
where b.pubid = p.pubid
and b.category in ('CHILDREN','COMPUTER')
group by p.name, b.category;

The above code returns the following:

在此处输入图片说明

Publisher Reed-N-Rite has an average retail below $50 - what needs to be added to my query so that I can filter the results from my statement to just those with retail > $50 ?

When you use aggregate function (like avg),you must use group by on other columns, And when you use group by ,you must use having for set where clause on aggregated column. Use Having for this:

select p.name, b. category, avg(b.retail)
from books b, publisher p 
where b.pubid = p.pubid
and b.category in ('CHILDREN','COMPUTER')
group by p.name, b.category 
having avg(b.retail) > 50

Add an HAVING clause to your query. HAVING applies to the group functions:

select p.name, b. category, avg(b.retail)
from books b, publisher p 
where b.pubid = p.pubid
and b.category in ('CHILDREN','COMPUTER')
group by p.name, b.category
having avg(b.retail) > 50;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM