我在编写 SQL 查询以在 % 模式下获取结果时遇到问题,我熟悉SQL ServerSUM()
的COUNT()
功能,但在查询内部实现逻辑时遇到问题,我希望得到以下形式的结果:-
UserName--- % of AccepectResult---- % of RejectResult
我的表结构是这样的,有两列Name
(用户名)和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
我正在尝试像这样编写此查询..
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
是否有任何其他方法可以编写此查询以及任何用于在 SQL Server 中计算百分比的内置函数?