我想列出所有年龄超过同一国籍人口平均年龄的人。涉及三个表:人,护照和国家。这就是我到目前为止所做的:
select round(months_between(sysdate, dob) / 12) as age, country.name, person.name, person.surname
from person
join passport on person.pid= passport.pid
join country on passport.cid= country.cid
where round(months_between(sysdate, dob) / 12) >
(select avg(round(months_between(sysdate, dob) / 12))
from person join passport on person.pid= passport.pid
join country on passport.cid= country.cid);
出于某种原因,我得到的结果不理想,低于平均年龄。同一国籍人口平均年龄的选择声明是:
SELECT avg(round(months_between(sysdate, dateofbirth) / 12)) as age, country.name
from person
join passport on person.personid = passport.personid
join country on passport.countryid = country.countryid
group by country.name;
我在上面的子选择中使用了 group by 子句。这样可以正常工作,但查询不能正确地生成结果,只有年龄大于平均年龄的人。
答案 0 :(得分:2)
这是分析函数的一个很好的用例:
SELECT *
FROM (select round(months_between(sysdate, dob) / 12) as age,
country.name country_name,
person.name person_first_name,
person.surname person_last_name,
avg(round(months_between(sysdate, dob) / 12))
over (partition by country.name ) avg_for_country
from person
join passport on person.pid = passport.pid
join country on passport.cid = country.cid
)
WHERE age > avg_for_country