2014-05-12 132 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值!