0

我在 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 位置库存率
------------------------------------------
一个 xx 2 10
一个 xy 5 20
总计 7 10

标准差 3 4
乙RT 6 10
总计 9 7


C FG 12 12
C GH 20 18
总计 32 15

**现在我想要一行 Total 行,其中存货总和和
显示费率总和。**

我想要的输出是


ID 位置库存率
------------------------------------------
一个 xx 2 10
一个 xy 5 20
总计 7 10

标准差 3 4
乙RT 6 10
总计 9 7


C FG 12 12
C GH 20 18
总计 32 15
总计 48 32

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

4

3 回答 3

0

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

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);
于 2013-09-01T16:56:32.580 回答
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()

于 2013-09-01T15:58:55.783 回答
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;
于 2013-09-01T15:59:06.147 回答