Introduction
This article explains how to use the Group By clause in a Stored Procedure in a Windows Forms application.
Stored Procedure
A Stored Procedure is a precompiled entity that executes on the database server itself. Stored Procedures are defined in the database by a "proc" or "procedure" keyword and variables are defined by the "@" character. Stored Procedures can be used to do SQL Injection. SQL Injeciton is the technique that allows SQL queries to be hidden from the front end. Stored Procedures are commonly used for security purposes. A Stored Procedure is a group of SQL statements that have been created and stored in the database. A Stored Procedure accepts input and output parameters as well, so that one Stored Procedure can be used over the network by various front ends using various input data.
Group By
The Group by clause allows us to group rows together and additionally can be performed with aggregate functions that work on a group of rows. The Group By clause works with the select command and groups the records of the tables values, and if aggregate functions are used in the select statements, then the Group By clause computes a summary value for each group.
Write the following procedure for creating a database and table in SQL Server:
Create database StudentResults
use StudentResults
create table StudentMarks
(
RollNo int,
FirstName varchar(max),
LastName varchar(max),
Subject varchar(max),
Marks int
)
Write the following procedure for inserting the values in table columns:
insert into StudentMarks (RollNo,FirstName,LastName,Subject,Marks) values(1,'Pankaj','Lohani','Math',70)
insert into StudentMarks (RollNo,FirstName,LastName,Subject,Marks) values(1,'Pankaj','Lohani','Physics',65)
insert into StudentMarks (RollNo,FirstName,LastName,Subject,Marks) values(1,'Pankaj','Lohani','Chemestry',75)
insert into StudentMarks (RollNo,FirstName,LastName,Subject,Marks) values(2,'Pravesh','Khanduri','Math',85)
insert into StudentMarks (RollNo,FirstName,LastName,Subject,Marks) values(2,'Pravesh','Khanduri','Physics',60)
insert into StudentMarks (RollNo,FirstName,LastName,Subject,Marks) values(2,'Pravesh','Khanduri','Chemestry',70)
insert into StudentMarks (RollNo,FirstName,LastName,Subject,Marks) values(3,'Nimit','Joshi','Math',90)
insert into StudentMarks (RollNo,FirstName,LastName,Subject,Marks) values(3,'Nimit','Joshi','Physics',60)
insert into StudentMarks (RollNo,FirstName,LastName,Subject,Marks) values(3,'Nimit','Joshi','Chemestry',75)
Write the query to execute the table schema:
select * from EmployeeInformation
Fig-tableschema
Create the following Stored Procedure for grouping the records:
create proc TotalMarks
as
begin
select FirstName, Sum(Marks) as TotalMarks
from StudentMarks
Group by FirstName
end
create proc MaxMarks
as
begin
select Subject, Max(Marks) as Highest_Marks
from StudentMarks
Group by Subject
end








Join the conversation! Your thoughts help the community grow.