我已经有了一个可以满足我需要的工作示例。 现在的问题是,我并不是真正的子查询粉丝,我认为可以有更好的解决方案解决这个问题。
所以这是我(已经)工作的例子:
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)可以相同(如示例所示)而无法工作
答案 0 :(得分:2)
假设对于一个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,你只想在总和中使用该子组中行的一个值(最高)。
是否"更好" (即性能更高)比原始查询更需要测试。子查询不一定是坏事;它们是一种工具,有时候它们是正确使用的工具。