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

眉间皱痕 提交于 2019-12-11 14:20:12

问题


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:

Determine the average retail price of books by publisher name and category. Include only the categories Children and Computer and the groups with an average retail price greater than $50.

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 ?


回答1:


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



回答2:


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;


来源:https://stackoverflow.com/questions/57075180/sql-oracle-12c-how-to-select-results-from-another-select-statement-nesting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!