Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
186 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...