Tuesday, May 24, 2016

SUM Using Group By (SQL)

At some point, you will be required to use the SQL GROUP BY clause with the SQL SUM function.  My time to use this was today and I thought I would create this post to help anyone else that may be needing to accomplish the same.
For example, you could also use the SQL SUM function to return the name of the department and the total sales (in the associated department).

Example Code:
SELECT department, SUM(sales) AS "Total sales"
FROM order_details
GROUP BY department;
Because you have listed one column in your SQL SELECT statement that is not encapsulated in the SQL SUM function, you must use the SQL GROUP BY clause. The department field must, therefore, be listed in the SQL GROUP BY section.
If you like this post and want to see more, follow me on my website www.chadcompton.com
Or if you prefer...