sql添加特定列

时间:2013-09-01 15:52:04

标签: sql oracle

我在oracle中有一个包含字段的表

  

ID,位置,库存,速率

select decode(grouping(id),1,'Total',id) id,loction,
sum(stock) stock,avg(rate) rate from product
group by rollup(id),location 

我有


ID    Location      stock         rate
------------------------------------------
A          xx          2             10
A          xy          5             20
Total                  7             10

B          SD          3             4
B          RT          6             10
Total                  9             7


C          FG          12            12
C          GH          20            18
Total                  32            15

**Now I want a row of Total rows where sum of stock and 
sum of rate is shown.**

My desired output is


ID    Location      stock         rate
------------------------------------------
A          xx          2             10
A          xy          5             20
Total                  7             10

B          SD          3             4
B          RT          6             10
Total                  9             7


C          FG          12            12
C          GH          20            18
Total                  32            15
Grand Total            48            32

注意:费率不是平均值,而是总行数的平均比率之和。

3 个答案:

答案 0 :(得分:0)

您可以使用UNION附加总数:

select decode(grouping(id),1,'Total',id) id,loction,
sum(stock) stock,avg(rate) rate from product
group by rollup(id),location 
UNION
select 'Grand Total','',sum(stock) stock,sum(rate) rate 
from product

如果您没有混合使用不同的聚合,则可以使用ROLLUP或使用分组设置获得总计,但我认为您不能获得SUM()总计AVG()小计。

答案 1 :(得分:0)

可能是这样的:

select decode(grouping(id),1,'Total',id) id,loction,
sum(stock) stock,avg(rate) rate from product
group by rollup(id),location 
union
select sum(stock), sum(rate) from
(
select decode(grouping(id),1,'Total',id) id,loction,
sum(stock) stock,avg(rate) rate from product
group by rollup(id),location 
) where id='Total' group by id;

答案 2 :(得分:0)

对所有列执行rollup将产生总计:

select (case when grouping(id) = 1 then 'Total' else id end) as id, loction,
       sum(stock) stock,avg(rate) rate
from product
group by rollup(id, location)

但是,您不希望location上的汇总。因此,您可以使用having子句对其进行过滤:

select (case when grouping(id) = 1 then 'Total' else id end) as id, loction,
       sum(stock) stock, avg(rate) rate
from product
group by rollup(id, location)
having not (grouping(product.location) = 1 and grouping(product.id) = 0);