我希望能够进行查询,以从不同组中选择平均值,但也可以从仅选择一个组中选择平均值。
下面是我正在使用atm的查询+简化表结构。
create table income_region (year int,region varchar(40),income float)
insert into income_region (income,region,year) values (2000,'North America', 2000)
insert into income_region (income,region,year) values(2200,'Europe', 2000)
insert into income_region (income,region,year) values(2101,'North America', 2001)
insert into income_region (income,region,year) values(2001,'Europe', 2001)
insert into income_region (income,region,year) values(2400,'North America', 2000)
select avg(income) as avg_income ,region,year as year
from income_region group by region,year with rollup
上述查询的问题是,当year也是Null时,它只显示区域的Null。而我想要的是区域为Null且年份为2000的新行,而区域为Null且年份为2001的另一行。
因此,我们获得所有类型的变化作为输出(而不仅仅是年份)。它应该看起来像这样:
avg_income region year
2200 Europe 2000
2001 Europe 2001
2100.5 Europe Null
2200 North America 2000
2101 North America 2001
2167 North America Null
2140.4 Null Null
2200 Null 2000
2050.5 Null 2001
答案 0 :(得分:1)
不幸的是,MySQL不支持Cube或分组集修饰符,这使得这项工作很容易。 由于汇总确实形成了超级聚合的层次结构,因此您需要对结果进行合并以获取完整的聚合集合。
select avg(income) as avg_income ,region,year as year
from income_region group by region,year with rollup
Union all
Select avg(income) as avg_income ,null as region,year as year
from income_region group by year
HTH