Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using GROUP BY and OVER

Tags:

sql

sql-server

I'm trying to get the total sales grouped by year and country. This works as expected:

SELECT Year, Country, SUM([Total Sales])
FROM Table
GROUP BY Country, Year;

Then, I have to compare the contribution of each country to the total sales in a year. I did this:

SELECT Year, Country, SUM([Total Sales]),
    SUM([Total Sales]) OVER(PARTITION BY Year) 
FROM Table
GROUP BY Country, Year;

Which gives me this error:

Column 'Table.Total Sales' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

like image 881
Federico Avatar asked Sep 19 '16 17:09

Federico


1 Answers

You need to nest the sums:

SELECT Year, Country, SUM([Total Sales]),
       SUM(SUM([Total Sales])) OVER (PARTITION BY Year) 
FROM Table
GROUP BY Country, Year;

This syntax is a little funky the first time you see it. But, the window function is evaluated after the GROUP BY. What this says is to sum the sum of the total sales . . . exactly what you want.

like image 154
Gordon Linoff Avatar answered Nov 23 '22 21:11

Gordon Linoff