oracle sql添加额外的行

时间:2015-04-25 07:37:07

标签: sql oracle rollup

我有这样的数据

col1            col2                                col3        col3  
ABC COMPANY     OH, Akron - 3636 Copley Rd           $50.00     MMO64606
ABC COMPANY     OH, Akron - 3636 Copley Rd           $200.00    MMO64606
ABC COMPANY     OH, Akron - 3636 Copley Rd           $100.00    MMO64606
ABC COMPANY     OH, Beachwood - 23700 Commerce Park  $20.00     MMO64606
ABC COMPANY     OH, Beachwood - 23700 Commerce Park  $200.00    MMO64606
ABC COMPANY     OH, Beachwood - 23700 Commerce Park  $1,000.00  MMO64606

我需要输出像

col1            col2                                col3        col3  
ABC COMPANY     OH, Akron - 3636 Copley Rd           $50.00     MMO64606
ABC COMPANY     OH, Akron - 3636 Copley Rd           $200.00    MMO64606
ABC COMPANY     OH, Akron - 3636 Copley Rd           $100.00    MMO64606
                OH, Akron - 3636 Copley Rd Total     $350.00    
ABC COMPANY     OH, Beachwood - 23700 Commerce Park  $20.00     MMO64606
ABC COMPANY     OH, Beachwood - 23700 Commerce Park  $200.00    MMO64606
ABC COMPANY     OH, Beachwood - 23700 Commerce Park  $1,000.00  MMO64606
                OH, Beachwood - 23700 Commerce Park Total   $1,220.00   

我使用了汇总但是它的分组我获得了更多的行数, 请提出任何解决方案。

修改

select col1, col2,col3,sum(nvl(detailtype,0))
  from tab
  where rownum<10
  group by
  rollup(col1, col2,col3)

我试过这种方式我的原始查询是

select col1, col2,col3
  from tab
  where rownum<10

当我运行上述查询时,这只给出了9行我得到了27行,但这不是预期的

2 个答案:

答案 0 :(得分:1)

你可以在oralce中使用ROLLUP。

点击此链接http://oracle-base.com/articles/misc/rollup-cube-grouping-functions-and-grouping-sets.php中的“ROLLUP” 我发布的相同例子:

SELECT fact_1_id,
       fact_2_id,
       SUM(sales_value) AS sales_value
FROM   dimension_tab
GROUP BY ROLLUP (fact_1_id, fact_2_id)
ORDER BY fact_1_id, fact_2_id;

 FACT_1_ID  FACT_2_ID SALES_VALUE
---------- ---------- -----------
         1          1     4363.55
         1          2     4794.76
         1          3     4718.25
         1          4     5387.45
         1          5     5027.34
         1               24291.35
         2          1     5652.84
         2          2     4583.02
         2          3     5555.77
         2          4     5936.67
         2          5     4508.74
         2               26237.04
                         50528.39

答案 1 :(得分:1)

您可以将union all与部分金额一起使用:

select col1, col2, col3, col4 
from test 
union all
select null, col2, sum(col3), null 
from test
group by col2   
order by col2, col1

SQLFiddle demo

或使用cubegrouping_id

select col1, col2, sum(col3) col3, col4
from test 
group by cube(col1, col2, col3, col4)
having grouping_id(col1, col2, col3, col4) in (0, 11)

SQLFiddle demo

修改:在第一个查询中union all是正确的,而不是union