sql – Oracle获取不带子查询的不同组的总和

我已经有一个工作的例子,它完全符合我的需要.

现在的问题是,我不是真正的子查询的粉丝,我认为可以有更好的解决方案来解决这个问题.

所以这是我(已经)工作的例子:

with t as
(
select  'Group1' as maingroup,'Name 1' as subgroup, 'random' as random, 500 as subgroupbudget from dual
union all
select 'Group1','Name 1','random2',500 from dual
union all
select 'Group1','Name 2','random3', 500 from dual
union all
select 'Group2','Name 3','random4', 500 from dual
union all
select 'Group2','Name 4','random5',500 from dual
union all
select 'Group2','Name 5', 'random6',500 from dual
)
select
maingroup,
subgroup,
random,
(select distinct sum(subgroupbudget) over(partition by maingroup) from t b where a.maingroup=b.maingroup group by maingroup,subgroup,subgroupbudget) groupbudget
from t a
group by  maingroup, subgroup ,subgroupbudget, random
order by maingroup, subgroup

如您所见,with子句显示了包含数据的简化表.现在问题是最后一列是子组的预算.结果我需要maingroup的预算.这意味着我必须对maingroup中的所有值求和,但前提是子组不同(这里我需要某种不同的).

不幸的是简单

sum(distinct subgroupbudget) over(partition by maingroup)

将无法工作,因为数字(subgroupbudget)可以是相同的(如示例中所示)

最佳答案 假设对于一个maingroup / subgroup,subgroupbudget总是相同的(或者你只取该子组的最高值),这应该有效:

with t as (select  'Group1' as maingroup,'Name 1' as subgroup, 'random' as random, 500 as subgroupbudget from dual
           union all
           select 'Group1','Name 1','random2',500 from dual
           union all
           select 'Group1','Name 2','random3', 500 from dual
           union all
           select 'Group2','Name 3','random4', 500 from dual
           union all
           select 'Group2','Name 4','random5',500 from dual
           union all
           select 'Group2','Name 5', 'random6',500 from dual),
    t1 as (select maingroup,
                  subgroup,
                  random,
                  case when row_number() over (partition by maingroup, subgroup order by subgroupbudget desc) = 1 then subgroupbudget
                  end subgroupbudget
           from t)
select maingroup,
       subgroup,
       random,
       sum(subgroupbudget) over (partition by maingroup) groupbudget
from   t1;

MAINGROUP SUBGROUP RANDOM  GROUPBUDGET
--------- -------- ------- -----------
Group1    Name 1   random         1000
Group1    Name 1   random2        1000
Group1    Name 2   random3        1000
Group2    Name 3   random4        1500
Group2    Name 4   random5        1500
Group2    Name 5   random6        1500

实际上,对于一个maingroup / subgroup,你只想在总和中使用该子组中行的一个值(最高).

它是否比您的原始查询“更好”(即更高性能)是您必须测试的东西.子查询不一定是坏事;它们是一种工具,有时候它们是正确的工具.

点赞