本文是对我在此处发布的问题的引用:
SQL: Group by Rollup with multiple columns
我不够具体,查询需要处理3-5列(而不是简化示例中的2列),因此我尝试使用扩展示例:
create table income_region (year int,region varchar(40),income float, sex varchar(10))
insert into income_region (income,region,year,sex) values (2000,'North America', 2000,'Male')
insert into income_region (income,region,year,sex) values(2200,'Europe', 2000,'Male')
insert into income_region (income,region,year,sex) values (2000,'North America', 2000,'Female')
insert into income_region (income,region,year,sex) values(2200,'Europe', 2000,'Female')
insert into income_region (income,region,year,sex) values(2101,'North America', 2001,'Male')
insert into income_region (income,region,year,sex) values(2001,'Europe', 2001,'Male')
insert into income_region (income,region,year,sex) values(2101,'North America', 2001,'Female')
insert into income_region (income,region,year,sex) values(2001,'Europe', 2001,'Female')
以下是我尝试的少数查询(基于链接文章中答案的修改)之一,无法提供所需的输出:
select avg(income) as avg_income ,region,year as year,sex as sex
from income_region group by region,year,sex with rollup
Union all
Select avg(income) as avg_income ,null as region,year as year, null as sex
from income_region group by year,sex
上面的查询缺少的是“ year”列的空值。更具体地说,这些也是我想要插入的额外行。
Income Region Year Sex
2300 Europe Null Female
2101 Europe Null Male
2100.5 North America Null Male
2400 North America Null Female