HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

Compute the total of SUM(column)

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
totalthecolumncomputesum

Problem

I have this code that sums up the qty for a certain item (itemid) and by its product date code (proddte).

select sum(qty), itemid, proddte 
from testtable where .... 
group by itemid, proddte


What I want to do is to get the total of all qty regardless of itemid/proddte. I have tried:

select sum(qty), itemid, proddte, sum(qty) over() as grandtotal 
from testtable 
where .... 
group by itemid, proddte


But it says I should also have qty in the group by clause. If I did that, the result will not be equal to my expected result.

It does not absolutely need to be represented as a separate column, with the same value in every row. Any representation is accepted as long as I can display the overall total.

Solution

This is valid syntax, too:

sum(sum(qty)) over ()


It's a bit confusing when one sees it at first but you only have to remember that the window functions - e.g. sum() over () - are applied after the group by so everything that can appear in the select list of a group by query can be placed inside a window aggregate. So (the qty cannot but) the sum(qty) can be placed inside sum() over ():

select sum(qty), itemid, proddte, 
       sum(sum(qty)) over () as grandtotal  
from testtable 
where .... 
group by itemid, proddte ;


Having said that, I'd prefer the GROUPING SETS query provided by Aaron Bertrand. The total sum needs to be shown once and not in every row.

Also note that while the sum of sums can be used to calculate the total sum, if you wanted the total count, you'd have to use the sum of counts (and not the count of counts!):

sum(count(*)) over ()  as grand_count


And if one wanted the average over all the table, it would be even more complicated:

sum(sum(qty)) over ()
/ sum(count(qty)) over ()  as grand_average


because the average of averages is not the same as the average over all. (If you try the avg(avg(qty)) over () you'll see that it may yield a different result than the above grand average.)

Code Snippets

sum(sum(qty)) over ()
select sum(qty), itemid, proddte, 
       sum(sum(qty)) over () as grandtotal  
from testtable 
where .... 
group by itemid, proddte ;
sum(count(*)) over ()  as grand_count
sum(sum(qty)) over ()
/ sum(count(qty)) over ()  as grand_average

Context

StackExchange Database Administrators Q#140576, answer score: 10

Revisions (0)

No revisions yet.