簡體   English   中英

匯總-按小計金額過濾行

[英]Rollup - Filter rows by subtotal amounts 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)

因此,將大洲平均值的定義簡單地定義為該大洲所有行的平均值,則解決方案可以是:

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;

如果所有國家/地區的年數相同(行數相同),則兩種解決方案應得出相同的結果。 但是,如果國家/地區的年限可以不同,則必須選擇適合您要求的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM