【问题标题】:oracle sql: Persons older than the average age of persons with the same nationalityoracle sql: 比同国籍人平均年龄大的人
【发布时间】:2016-02-28 17:08:54
【问题描述】:

我想列出所有比具有相同国籍的人的平均年龄大的人。涉及三个表:person、passport 和 country。这是我到目前为止所拥有的:

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语句为:

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 子句。这可以正常工作,但查询仅针对年龄大于平均年龄的人无法正确生成结果。

【问题讨论】:

  • 提示;子查询中有太多连接。它应该与外部查询相关。
  • 我从 subselect 中删除了所有连接,但输出中仍然出现不想要的结果。 @GordonLinoff

标签: sql oracle


【解决方案1】:

这是一个很好的分析函数用例:

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

【讨论】:

  • 感谢您的回答,但出现错误:ORA-00923: FROM keyword not found where expected [SQL State=42000, DB Errorcode=923] 执行此代码时。 @Matthew McPeak
  • 似乎只是一个错字:partition by ( country.name ) --> OVER (PARTITION BY country.name)
  • 谢谢!效果很好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多