I m facing a problem to write a SQL query to get result in % mode, I am familer with SUM() and COUNT() functions of SQL Server but facing problem to implement logic inside query I want result in below form:-
UserName--- % of AccepectResult---- % of RejectResult
My table structure is like this with two columns Name (UserName) and Result :
NAME Result
---------------
USer1 A
USer1 A
USer1 A
USer1 R
USer1 R
USer1 A
USer2 A
USer2 A
USer2 A
USer2 A
USer2 R
A - Accepted Result
R - Rejected Result
I’m trying to write this query like this..
select * into #t1 from
(
select UserName , count(Result) as Acc
from Test where result = 'A'
group by UserName
) as tab1
select * into #t2 from
(
select UserName , count(Result) as Rej
from Test where result = 'R'
group by UserName
) as tab2
select #t1.UserName ,
#t1.Acc ,
#t2.Rej ,
(#t1.Acc)*100/(#t1.Acc + #t2.Rej) as AccPercentage,
(#t2.Rej)*100/(#t1.Acc + #t2.Rej) as RejPercentage
from #t1
inner join #t2 on #t1.UserName = #t2.UserName
drop table #t1
drop table #t2
Is there any other way to write this query and any built-in function for calculating percentage in SQL Server?
You do not require to join table. Instead you can use
SUMorCOUNTfunction like this:Using
SUMFunction:Or using
COUNTFunction:Or using
SubQuery:See this SQLFiddle