• 17. 11. 2019
  • Ing. Jan Zedníček - Data Engineer & Controlling
  • 0

GROUP BY clause is used to group data. In most of the cases, we talk of a situation when we need to make an aggregate operation in the table (sum of sales, number of records, average, etc.)

GROUP BY in SQL Script

  1. SELECT
  2. FROM
  3. WHERE
  4. GROUP BY
  5. HAVING
  6. ORDER BY

Syntax

SELECT [Column 1], [Column 2], Aggregate_function([Column 3]) AS Alias
FROM Table
GROUP BY Column 1, Column 2

We will use this clause in most cases of aggregate function usage. Adding operator OVER( PARTITION BY | ORDER BY | ROW | RANGE) is the only exception. This operator requires advanced skills and therefore we will not waste our time with it. The rule for beginners is that the clause is mandatory whenever there is any aggregate function in SELECT.

Example

Let’s have a table [FactInternetSales]. We will work with 2 fields:

  • Date [OrderDate]
  • Amount [SalesAmount]

group by example in sql

We want to aggregate the amount according to dates. The result will be in descending order. We will use:

SELECT
[OrderDate]
,SUM([SalesAmount]) AS [SalesAmount]
FROM [AdventureWorksDW2014].[dbo].[FactInternetSales]
GROUP BY [OrderDate]
ORDER BY [OrderDate] DESC

and the result:

group by clause in sql script

If we would miss out the clause, the result will be error: “Column ‘AdventureWorksDW2012.dbo.FactInternetSales.OrderDate’ is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.”

Rate this post

Ing. Jan Zedníček - Data Engineer & Controlling

My name is Jan Zedníček and I have been working as a freelancer for many companies for more than 10 years. I used to work as a financial controller, analyst and manager at many different companies in field of banking and manufacturing. When I am not at work, I like playing volleyball, chess, doing a workout in the gym.

🔥 If you found this article helpful, please share it or mention me on your website

Leave a Reply

Your email address will not be published. Required fields are marked *