Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAbdullah Jassim
4,551 PointsWhy does the GROUP BY Function in SQL add more names. It isnt just suppose to cluster together rows together?
In the SQL playground. The question is: -- What is the sum of all sales by rep and location?
I wrote: SELECT SalesRep.LastName, SUM(Sale.SaleAmount) AS SalesAmount, Location.LocationName FROM SalesRep INNER JOIN Sale ON SalesRep.SalesRepID = Sale.SalesRepID INNER JOIN Location ON Location.LocationID = Sale.LocationID
It returned: Schwartz, 883,849 and AutoSellers Columbia...
However, when I add the GROUP BY function it gives me more data. I dont understand how that works... I thought group by just clusters data together. Why do I have to add group by function to get more salesrep names and their respect sales amount?
1 Answer
Steven Parker
231,269 PointsWithout GROUP BY
, the aggregate function works on every row of the table, and you get a single row with the total. The other data shown with it is probably not particularly useful.
But with GROUP BY
, the rows are clustered together and the aggregate applies to each separate cluster. So the output has a row for each cluster, and the terms used in the grouping clause will be meaningful to the totals.