SQL Oracle query to calculate subtotal

泄露秘密 提交于 2019-12-12 05:12:56

问题


I am googling to find proper way to make subtotals in 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

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

P.S. 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). Like below

MODEL  SIFRA     VELICINA  SUMA

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

回答1:


This appears to be a good time to use 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. with magacin summed by those 3 fields...

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. This approach is using an analytic/window function.




回答2:


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


来源:https://stackoverflow.com/questions/43979507/sql-oracle-query-to-calculate-subtotal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!