Search This Blog

Percentage Calculation of a Numeric column in SQL

Percentage Calculation of a Numeric column in SQL 

In below example we are calculating Salary percentage of Each Employee .

Sample Data

a-5000
b-8000
c- 10000
d-5000
e-3000

Formula for Percentage = SalaryofeachEmployee*100/sumofSalaryofEmployee
Eg -A Salary Percentage  %   =5000*100/23000 


So in the Above Records u can see that we want EmployeePercentage Salary for each employee

So we will create a sample Table with some employee Records and we will calculate there Salary Percent


CREATE TABLE [dbo].[Employee_SPercent](
[Empid] [int]  NOT NULL,
[EmpName] [nvarchar](50) NULL,
[EmpSalary] [float] NULL
) ON [PRIMARY]
GO

INSERT [dbo].[Employee_SPercent] ([Empid], [EmpName], [EmpSalary]) VALUES (1, N'sumit', 5000)
INSERT [dbo].[Employee_SPercent] ([Empid], [EmpName], [EmpSalary]) VALUES (3, N'amit', 8000)
INSERT [dbo].[Employee_SPercent] ([Empid], [EmpName], [EmpSalary]) VALUES (5, N'vijay', 10000)
INSERT [dbo].[Employee_SPercent] ([Empid], [EmpName], [EmpSalary]) VALUES (7, N'suresh', 5000)
INSERT [dbo].[Employee_SPercent] ([Empid], [EmpName], [EmpSalary]) VALUES (9, N'Mukesh', 3000)


--Query that will Give SalaryPercent of Each Employee

select empname,empsalary, x.Totalsalary ,(EmpSalary /Totalsalary)*100 as SalaryPercent from [Employee_SPercent] join 
(select SUM(empsalary)Totalsalary from [Employee_SPercent])x on 1=1

Output
empname empsalary SalaryPercent
sumit 5000 16.1290322580645
amit 8000        25.8064516129032
vijay 10000 32.258064516129
suresh 5000 16.1290322580645

Mukesh 3000 9.67741935483871


If you want the percentage upto two round figure cast it to decimal

select empname,empsalary ,cast((EmpSalary /Totalsalary)*100 as decimal(16,2)) as SalaryPercent from [Employee_SPercent] join 
(select SUM(empsalary)Totalsalary from [Employee_SPercent])x on 1=1

Output
empname empsalary SalaryPercent
sumit 5000 16.13
amit 8000        25.81
vijay 10000 32.26
suresh 5000 16.13

Mukesh 3000 9.68

If you want percentage of each employee not salary then use below query

select EmpName , count(*) * 100 / sum(count(*)) over() as percnt
from [Employee_SPercent]
group by Empname

Output
EmpName percnt
amit         20
Mukesh 20
sumit 20
suresh 20
vijay 20

NOTE: The formula of calculating percentage can change according to the requirement.

No comments:

Post a Comment