Oracle SQL:添加行以选择结果

时间:2014-05-12 15:34:42

标签: sql oracle

说我有一个包含列的表:id, group_id, type, val
选择的一些示例数据:
1, 1, 'budget', 100
2, 1, 'budget adjustment', 10
3, 2, 'budget', 500
4, 2, 'budget adjustment', 30

我希望结果看起来像是 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

请告知,
感谢。

4 个答案:

答案 0 :(得分:2)

这将为您提供所需的两行,但不是您想要的ID和类型的值。

Oracle示例:http://docs.oracle.com/cd/B19306_01/server.102/b14223/aggreg.htm

Select id, group_id, type as myType, sum(val) as sumVal
FROM Table name
Group by Grouping sets ((id, group_id, type, val), (group_ID))

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分: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 post的延续,具有id值!