简体   繁体   English

SQL Oracle查询以计算小计

[英]SQL Oracle query to calculate subtotal

I am googling to find proper way to make subtotals in Oracle SQL. 我正在寻找在Oracle SQL中进行分类汇总的正确方法。 Recording to this i make query 记录到此我查询

select model,  sifra, velicina, sum(nvl(magacin,0)) as suma
from podmornica
where model ='30001'
group by  sifra, velicina, cube (model)
order by model, sifra, velicina

I have table podmornica with columns:model, sifra, velicina, magacin 我的桌子上有列podmornica,其列为:model,sifra,velicina,magacin

But it doesn't work. 但这是行不通的。 Every second row in column model is null, and at the end not calculate sum. 列模型中的第二行均为空,最后不计算总和。 How to solve this? 如何解决呢? Thanks 谢谢

PS In one MODEL we have variations of SIFRA, i wan't as result to have subtotals for each SIFRA for one model (in this case model is 30001). PS在一个模型中,我们有SIFRA的变体,因此我不会为一个模型(在这种情况下,模型为30001)的每个SIFRA小计。 Like below 像下面

MODEL  SIFRA     VELICINA  SUMA

30001  3000101      0        1
30001  3000102      0        2
30001  3000103      0        5
______________________________
30001                        8

This appears to be a good time to use group by grouping sets ... 这似乎是使用group by grouping sets的好时机...

SELECT MODEL,  SIFRA,     VELICINA,  sum(nvl(magacin,0)) as SUMA
FROM podmornica
WHERE model ='30001'
GROUP BY GROUPING SETS ((MODEL, SIFRA, VELICINA), (Model))

Group by the model, sifra and velicina to get the detail rows. 按模型,sifra和velicina分组以获取详细信息行。 with magacin summed by those 3 fields... 加上这3个领域的magacin ...

Group by model so that the sum total is shown for a given model. 按模型分组,以便显示给定模型的总和。

Alternatively if you wanted to add a column, you could show the total on every line for the model by adding a sum(magacin) over (partition by model) as sumB to the select. 另外,如果您想添加一列,则可以通过将sum(magacin) over (partition by model) as sumB添加到选择中,从而显示模型每一行的总数。 This approach is using an analytic/window function. 这种方法正在使用分析/窗口功能。

It might be hard to find exactly what you want, but I think you need to cube all the columns: 可能很难找到所需的确切内容,但我认为您需要对所有列进行多维数据集处理:

select model, rgrupa, sifra, velicina, sum(nvl(magacin,0)) as suma
from podmornica
where model ='30001'
group by cube(model, rgrupa, sifra, velicina)
order by model,rgrupa, sifra, velicina

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM