2014-05-12 56 views
1

說我有一個列的表格:id, group_id, type, val
從選擇一些示例數據:
1, 1, 'budget', 100
2, 1, 'budget adjustment', 10
3, 2, 'budget', 500
4, 2, 'budget adjustment', 30的Oracle SQL:添加行選擇結果

我想要的結果看起來像
1, 1, 'budget', 100
2, 1, 'budget adjustment', 10
5, 1, 'budget total', 110
3, 2, 'budget', 500
4, 2, 'budget adjustment', 30
6, 2, 'budget total', 530

請指教,
感謝。

+0

會空ID和空類型的工作?如果是這樣,則按組進行分組,否則使用公共表表達式來選擇計數和顯示預算總數。 – xQbert

+0

檢查Oracle的[RollUp](http://www.oracle-base.com/articles/misc/rollup-cube-grouping-functions-and-grouping-sets.php)命令 – Serpiton

回答

1

由於@Serpiton建議,看來你真的需要的功能,是小計添加到您的能力結果集,這表明rollup是您需要的。用法是這樣的:

SELECT id, 
     group_id, 
     coalesce(type, 'budget total') as type, 
     sum(val) as val 
FROM  your_table 
GROUP BY ROLLUP (group_id), id, type 
0

可以使用UNION ALL更行添加到原來的選擇。

select group_id,type,val from tableA 
union all 
select group_id, 'budget total' as type,sum(val) as val from tableA group by group_id,type 

要顯示正確的順序和id,你可以使用嵌套選擇

select rownum, group_id,type,val from (select group_id,type,val from tableA 
union all 
select group_id, 'budget total' as type,sum(val) as val from tableA group by group_id,type) order by group_id asc 
0
with foo as 
(select 1 group_id, 'budget' type, 100 val 
    from dual 
    union 
    select 1, 'budget adjustment', 10 
    from dual 
    union 
    select 2, 'budget', 500 
    from dual 
    union 
    select 2, 'budget adjustment', 30 
    from dual) 
SELECT rank() over(order by type, group_id) rk, 
     group_id, 
     nvl(type, 'budget total') as type, 
     sum(val) as val 
    FROM foo 

group by Grouping sets((group_id, type, val),(group_id)) 

它就是xQbert後的延續,有ID值!