【问题标题】:How to use rollup function in oracleoracle中如何使用rollup函数
【发布时间】:2015-10-22 16:41:12
【问题描述】:

我正在尝试使用 group by rollup oracle 函数,但不正确。

这是我的数据格式(L1_Proj_ID 是 1 级项目 ID 等.....)

Proj_ID  Hours_Charged L1_Proj_ID  L2_Proj_ID L3_Proj_ID     L4_Proj_ID  
-------------------------------------------------------------------------  
1100.10         20       1100        1100.10    Null           Null  
1100.11.01      30       1100        1100.11    1100.11.01     Null  
1100.11.02      40       1100        1100.11    1100.11.02     Null  
1100.12.01.01   50       1100        1100.12    1100.12.01     1100.12.01.01  

我需要得到汇总,我的输出应该是

Proj_Level  Hours_Charged  
--------------------------  
1100            140  
1100.10          20  
1100.11          70  
1100.11.01       30  
1100.11.02       40   
1100.12          50   
1100.12.01       50  
1100.12.01.01    50  

请告诉我是否还有其他简单的方法。

到目前为止,我可以像...一样获取这些数据

select 
  L1_proj_id, 
  sum(hours_charged) as hours_charged 
from table  
group by 
  l1_proj_id 
union all   
select 
  L2_proj_id, 
  sum(hours_charged) as hours_charged 
from table 
group by 
  21_proj_id  
union all  
select 
  L3_proj_id, 
  sum(hours_charged) as hours_charged 
from table 
group by 
  l3_proj_id  
union all  
select 
  L4_proj_id, 
  sum(hours_charged) as hours_charged 
from table 
group by 
  l4_proj_id

【问题讨论】:

  • 你的数据结构很奇怪。 ROLLUP(col1, col2) 为您提供以下汇总结果: GROUP BY col1, col2;按 col1 分组;没有 GROUP BY。但是,您的 id 位于 5 个不同的列中。
  • @NeriaNachum 到目前为止,我可以通过 l1_proj_id 从表组中选择 L1_Proj_ID,求和(hours_charged)Hours_charges union all select L2_Proj_ID,从表组中求和(hours_charged)Hours_charges by l2_proj_id union all select L3_Proj_ID , sum (hours_charged) Hours_charges from table group by l3_proj_id union all select L4_Proj_ID, sum (hours_charged) Hours_charges from table group by l4_proj_id
  • 我就是这么想的。它不漂亮,但我不完全理解为什么你有 5 个 id 的列代表相同的 id(?)。例如,与其使用这样的一行:1100.10 20 1100 1100.10,不如使用这样的三列:1100.10 20; 1100 20; 1100.10 20;

标签: sql oracle rollup


【解决方案1】:

这不使用rollup,但我认为它可能会提供您的结果。本质上,我将您的列取消嵌套成行。如果您的内容发生变化,它也应该相对易于扩展。

with levels as (
  select level id
  from dual
  connect by level <= 4
),
all_data as (
  select
    case l.id
      when 1 then l1_proj_id
      when 2 then l2_proj_id
      when 3 then l3_proj_id
      when 4 then l4_proj_id
    end as project_id,
    t.hours_charged
  from
    table t,
    levels l
)
select
  project_id, sum (hours_charged) as hours_charged
from all_data
where project_id is not null
group by project_id

【讨论】:

    猜你喜欢
    • 2018-07-18
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 2014-03-06
    • 2011-10-12
    • 2021-12-19
    相关资源
    最近更新 更多