日期:2014-05-17  浏览次数:20664 次

oracle sql 報表匯總的問題
現在在做報表 需要給出的格式

id number name
1 10 i
2 20 i
3 30 i
'' 60 '小記'
4 10 j
5 20 j
6 30 j
'' 60 '小記'
'' 120 '合計'

現在做的方式是
select * from AA
union all
select '', sum(number),'小記' from AA group by name
union all
select '',sum(number),'合計' from AA

由於AA是一個複雜的查詢 用我這種方式寫的需要重複寫3次 這樣會造成需要些大量的代碼
有什麽其他的寫法 讓代碼可以簡短些

------解决方案--------------------
SQL code
SELECT * FROM AA
UNION ALL
select '' ID,SUM(NUMBER),NAME from aa
GROUP BY CUBE(NAME)

------解决方案--------------------
rollup
------解决方案--------------------
SQL code
With t As (
  select 1 Id,10 numb, 'i' Name From dual Union All
  select 2 Id,20 numb, 'i' Name From dual Union All
  select 3 Id,30 numb, 'i' Name From dual Union All
  select 4 Id,10 numb, 'j' Name From dual Union All
  select 5 Id,20 numb, 'j' Name From dual Union All
  select 6 Id,30 numb, 'j' Name From dual
)
SELECT id, SUM(numb) numb, decode(grouping_id(id, NAME), 3, '合计', 2, '小記', NAME) NAME
  FROM t
 GROUP BY ROLLUP(NAME, Id)