2014-09-16 3 views
0

테이블과 쿼리가 있다고 가정하면 주어진 대륙에서 특정 국가에 대한 인구로 구성된롤업 - 소계 금액으로 행 필터링 sql oracle

입니다.
국가의 인구가 대륙보다 큰 경우 평균 인구 평균 (인구) & 대륙 평균 인구 +3 기본적으로 소계 대륙 값과 일정한 차이가있는 행을 필터링하려고합니다.

데이터를 수정하고 데이터가 여러 해가 아니며 숫자가 분명히 가비지라는 것을 알았지 만 이는 단지 예일뿐입니다.

create table abc (continent varchar2(30), country varchar2(30), population number, yr number) 
insert into abc values ('africa', 'kenya', 50, 2005) 
insert into abc values ('africa', 'egypt', 100, 2006) 
insert into abc values('africa', 'south africa', 35, 2007) 
insert into abc values ('africa', 'nigeria', 200, 2008) 
insert into abc values ('asia', 'china', 50, 2005) 
insert into abc values ('asia', 'india', 100, 2006) 
insert into abc values('asia', 'japan', 35, 2007) 
insert into abc values ('asia', 'korea', 200, 2008) 


select continent, country, avg(population) 
from abc 

where ------population for each country > 3+ avg for each continent 
----should return egpyt/nigeria rows and india/korea rows since average here is 96.25 for each continent. 
group by rollup(continent, country) 
+0

나는 당신의 테이블을 가정하고 싶지 않습니다. 귀하의 테이블 구조와 예상/실제 출력을 보여주십시오. – CodeNewbie

+0

샘플 데이터로 삽입 문도 거의 없습니다. –

+0

안녕하세요, 저는 신속하게 아이디어를 얻으려는 몇 가지 진술을 추가했습니다. 소계 행에서 특정 거리 떨어져있는 행을 필터링하려고합니다 --- select 문에서 두 번째 열이 NULL 인 곳입니다. – runningbirds

답변

1

그래서, 단순히 대륙과 모든 행의 평균 인 것으로 대륙 평균의 정의, 해결책이 될 수 있습니다

select continent 
    , country 
    , avg(population) country_avg 
    , max(continent_avg) continent_avg 
    from (
    select continent 
     , country 
     , population 
     , avg(population) over (
      partition by continent 
     ) continent_avg 
    from abc 
) 
group by continent, country 
having avg(population) > max(continent_avg) + 3 
order by continent, country; 

내가 대륙 평균의 정의에 대해 질문 이유는 대륙 내의 일부 국가에서 더 많은 행이있는 경우 (= 더 많은 년), 해당 국가는 그와 같이 계산 된 평균치가 더 커지게됩니다. 그런 다음 대안은 대륙 평균이 해결책이 될 수있는 경우에 국가 평균의 평균이라고 할 수있다 : 국가 모든 년 같은 수의 (행의 같은 수의)가있는 경우

select * 
    from (
    select continent 
     , country 
     , avg(population) country_avg 
     , avg(avg(population)) over (
      partition by continent 
     ) continent_avg 
    from abc 
    group by continent, country 
) 
where country_avg > continent_avg + 3; 

의 두 가지 해결책은 동일한 결과를 제공해야합니다. 그러나 국가의 연수가 다를 수 있다면 요구 사항에 맞는 솔루션을 선택해야합니다.

+0

# 1 내가 고맙다고 생각했던 것이 었습니다! 제 2의 해결책에 대해서도 고맙습니다. 저는이 문제를 시각화하고 해결하는 방법을 이해하는데 도움이된다고 생각합니다. – runningbirds