Languages
[Edit]
EN

MS SQL Server - GROUP BY multiple columns

0 points
Created by:
Dirask JS Member
3460

In this article, we would like to show you how to use GROUP BY statement with multiple columns in MS SQL Server.

Quick solution:

SELECT [column1], [column2], [columnN]
FROM [table_name]
WHERE condition
GROUP BY [column1], [column2], [columnN]
ORDER BY [column_name];

Practical example

To show how GROUP BY with multiple columns works, we will use the following table:

MS SQL Server - example data used with GROUP BY multiple columns
MS SQL Server - example data used with GROUP BY multiple columns
 

Note:

At the end of this article you can find database preparation SQL queries.

Example

In this example, we will display the number of users with the same name and department_id.

Query:

SELECT [name], [department_id], COUNT(*)
FROM [users]
GROUP BY [name],[department_id]
ORDER BY [name];

Result:

MS SQL Server - GROUP BY multiple columns result
MS SQL Server - GROUP BY multiple columns result

Result explanation:

As we see, the COUNT(*) column contains the number of users with the same name and department_id. For example, there are three people named Ailisa in the department 3.

Database preparation

create_tables.sql file:

CREATE TABLE [users] (
	[id] INT IDENTITY(1,1),
	[name] VARCHAR(50) NOT NULL,
	[surname] VARCHAR(50) NOT NULL,
	[department_id] INT,
    [salary] DECIMAL(15,2) NOT NULL,
	PRIMARY KEY ([id])
);

insert_data.sql file:

INSERT INTO [users]
	( [name], [surname], [department_id], [salary])
VALUES
	('John', 'Stewart', 1, '2000.00'),
	('Chris', 'Brown', 3, '2000.00'),
	('Chris', 'Lewis', 3, '2000.00'),
	('Kate', 'Lewis', 3, '2000.00'),
	('Kate', 'Stewart', 3, '2000.00'),
	('Ailisa', 'Lewis', 3, '2000.00'),
	('Ailisa', 'Gomez', 3, '3000.00'),
	('Gwendolyn', 'James', 2, '3000.00'),
	('Simon', 'James', 2, '2000.00'),
	('Simon', 'Brown', 3, '2000.00'),
	('Simon', 'Collins', 3, '3000.00');

MS SQL Server - problems

MS SQL Server - GROUP BY multiple columns
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join