首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQL:具有多列的Group by Rollup

SQL:具有多列的Group by Rollup
EN

Stack Overflow用户
提问于 2019-02-26 19:09:09
回答 1查看 922关注 0票数 0

我希望能够执行一个查询,从不同的组中选择平均值,但也可以在仅选择其中一个组的情况下选择平均值。

下面是我使用的自动柜员机的查询+简化表结构。

代码语言:javascript
复制
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时,它仅显示region为Null。而我想要的是region为Null,year为2000的新行。另一个是region为Null,year为2001。

因此,我们得到了所有类型的变化作为输出(而不仅仅是年份)。它应该看起来像这样:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-26 19:53:38

不幸的是,MySQL既不支持多维数据集,也不支持分组集修饰符,这使得这项任务变得很容易。由于rollup确实形成了超级聚合的层次结构,因此您将需要联合结果以获得完整的聚合集。

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54884165

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档