1

I'm struggling with a SQL aggregate function. I need to run SUM function and GROUP BY, but at the same time add total without grouping as a measuring data. Here is a simple demo dataset:

select a.item, sum(a.value) from SALES a
group by a.item, a.region

Result is essentially this:

SALES       
    ITEM    REGION  Sum(Value)
    Apple   North      4
    Orange  South      7
    Apple   South      3
    Apple   East       5
    Orange  East       6
    Orange  North      5

This works fine to summarize item sales and group them based on region and item. What I'm missing though is that I'm not after summarized values per se, but rather the ratios of sales by region.

I.e. Apples sold 4 + 3 + 5 over different regions, so 12 in total and I'm looking for the sales share of each region in total sales. If I could only present sales ratios in the query without actual sales numbers, even better, however not crucial.

I'm currently after how to add another column where all sales of Apples or Oranges would be summarized in a separate column, so I could divide them to get an answer, but I'm not sure how to do that nor am I sure if that's the right way to move forward.

But it would be looking for something like that:

SALES           
    ITEM    REGION  Value   Total
    Apple   North   4        12
    Orange  South   7        18
    Apple   South   3        12
    Apple   East    5        12
    Orange  East    6        18
    Orange  North   5        18

I'm not sure on the db engine, but regular SQL seems to work. I will end up running this query from Excel, so I could utilize Excel tools to divide region sales with total sales to get the shares, however if this could be handled by the query itself, then it would clearly be far superior.

Any help is much appreciated!

1
  • Tag your question with the database you are using. Commented Oct 3, 2018 at 21:33

1 Answer 1

1

I think you just want a window function:

select s.item, s.region, sum(s.value),
       sum(sum(s.value)) over (partition by item) as region_total
from SALES s
group by s.item, s.region;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.