Oracle SQL分组元素

时间:2017-02-03 18:12:58

标签: sql oracle group-by

我知道这个问题有点微不足道但我在编写下面的例子中的SQL时遇到了困难。 如第一个表所示,是我生成的结果,它们可以用于分析,

REGION  SUBREGION    SUM
------  ---------    ------
CORP    CORP1       5  
CORP    CORP2       10 
CORP    CORP3       5 
SB      SB1         10 
SB      SB2         10 
MID     null        10 
LARGE   null        20 

但是对于摘要报告,我需要显示结果,如第二个表所示。有线索吗?

REGION  SUM
------  ----
CORP    20
CORP1   5
CORP2   10
CORP3   5
SB      20
SB1     10
SB2     10
MID     10
LARGE   20

4 个答案:

答案 0 :(得分:1)

只需将现有的GROUP BY更改为GROUPING SET

SELECT
   Coalesce(subregion, region) AS region,
   Sum(column)
FROM mytable
GROUP BY GROUPING SETS(region, subregion)
HAVING Coalesce(subregion, region) IS NOT NULL

答案 1 :(得分:0)

听起来你需要通过不同的字段聚合同一个表,但要把它们都拿回来,好像它是一个字段一样。想到的解决方案是UNION

select sum() as sum, REGION as sf from table group by REGION
union ALL
select sum() as sum, SUB_REGION as sf from table group by SUB_REGION;

希望有所帮助

基于丹的问题,我补充一点,如果你不想加入vals,只需取出总和并分组并做直接联合

 select REGION as sf from table 
    union ALL
    select  SUB_REGION as sf from table;

编辑: 还有一个想法,也许当你首先进行查询时,你可能想要查看ROLLUP的概念作为你的组bu和agg函数的附加条款,可能有助于一次解决这个问题。

答案 2 :(得分:0)

尝试使用OLAP函数rollupgrouping,如下所示:

select 
  nvl(subregion, region) region, sum("sum")
from  t
group by region, rollup(subregion)
having case when count(*) = 1 then 0 else 1 end = grouping(subregion);

在上面,

having case when count(*) = 1 then 0 else 1 end = grouping(subregion);

如果该区域只有一行,则上面排除了汇总行,因此没有重复。

另外,请避免在标识符中使用保留关键字,例如sum或count。

演示:

SQL> with t(REGION ,SUBREGION    ,s) as (
  2  select 'CORP'   , 'CORP1'   , 5  from dual union all
  3  select 'CORP'   , 'CORP2'   , 10 from dual union all
  4  select 'CORP'   , 'CORP3'   , 5  from dual union all
  5  select 'SB'        ,'SB1'          ,10  from dual union all
  6  select 'SB'        ,'SB2'          ,10  from dual union all
  7  select 'MID'       , null   , 10    from dual union all
  8  select 'LARGE'  ,  null   , 20   from dual
  9  )
 10  select
 11    nvl(subregion, region) region, sum(s)
 12  from  t
 13  group by region, rollup(subregion)
 14  having case when count(*) = 1 then 0 else 1 end = grouping(subregion);

REGIO     SUM(S)
----- ----------
SB1           10
SB2           10
SB            20
MID           10
CORP1          5
CORP2         10
CORP3          5
CORP          20
LARGE         20

9 rows selected.

SQL>

答案 3 :(得分:0)

通过查询执行相同的组,但尝试使用ROLLUP分组:

像(未经测试)的东西:

select region, subregion, sum(some_column) as sum
from some_table
group by rollup(region, subregion)
order by region, subregion;