【问题标题】:Rollup - Filter rows by subtotal amounts sql oracle汇总 - 按小计金额筛选行 sql oracle
【发布时间】:2014-09-16 05:22:36
【问题描述】:

假设我有一个表和查询:

由给定年份的给定大陆上给定国家的人口组成。
如果国家的人口大于大陆+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 语句中的第二列为 NULL 的地方。
  • 丢失汇总并使用HAVING:docs.oracle.com/database/121/SQLRF/…
  • 我想过有,但我不知道如何用它来做一个相对简洁的查询

标签: sql oracle rollup


【解决方案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;

如果所有国家/地区都有相同的年数(相同的行数),则两种解决方案应该给出相同的结果。但是,如果国家/地区可以有不同的年数,您将不得不选择适合您要求的解决方案。

【讨论】:

  • #1 是我一直在寻找的东西,非常感谢!也感谢您提供第二个解决方案,我认为这有助于我理解如何更好地可视化和解决此类问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-11
  • 2019-07-22
  • 1970-01-01
  • 2021-04-08
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多