Introduction:

  • In this article we will explain how to use SUM Function in SQL Server OR what is SUM Function in SQL Server with Example.
  • Description:

The SQL server SUM() function returns the total sum of a numeric column.

Let's see the Syntax for the select sum function:

SELECT SUM (expression)  
FROM tables 
WHERE conditions;

 

Column may be numeric field or formula. The following All Student Record:


select s.Id,s.Name,s.Mobile,s.address1 as
[Address], f.amount as Fee from
Student s inner join Fee f on s.id=f.StudentId

Result:


After using this SQL SELECT SUM example, it will make the result containing the sum of the Fee greater than 2000.

Total Fee: 84000.00


  • SQL SUM EXAMPLE with single column:

If you want to know how the combined total fee of all student whose fee is above 2000.

select SUM(f.amount) as Fee from Student s
inner join Fee f on s.id=f.StudentId
WHERE f.amount > 2000

In this example, you will find the expression as "Total Fee" when the result set is returned.


  • SQL SUM Example with SQL Distinct:

    You can also use SQL DISTINCT clause with SQL SUM function.

select SUM(distinct f.amount) as Fee from Student s 
inner join Fee f on s.id=f.StudentId
WHERE f.amount > 2000

After using this SQL SELECT distinct SUM example, it will make the result containing the sum of the Fee greater than 2000.

Total Fee: 72000.00


  • SQL SUM EXAMPLE with SQL GROUP BY:

Sometimes we have to need use the SQL GROUP BY statement with the SQL SUM function. For example, we could also use the SQL SUM function to return the Name and the total Fee.

select s.Name ,SUM(distinct f.amount) as Fee from Student s inner join Fee f on  
 s.id=f.StudentId Group by s.Name
 

Let us see students Record:


 


After using the SQL GROUP BY statement with SUM, you will find the following result.




I hope this article will help to you.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

you may also like