是否有任何内置函数来计算SQL Server中的百分比

时间:2012-08-30 10:52:32

标签: sql sql-server percentage

我在编写SQL查询以获得%模式的结果时遇到问题,我对SQL Server的SUM()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中百分比的任何内置函数?

3 个答案:

答案 0 :(得分:4)

您不需要加入表格。相反,您可以使用SUMCOUNT这样的功能:

使用SUM功能:

SELECT Name, 100 * 
SUM(CASE WHEN Result = 'A' THEN 1 ELSE 0 END)/COUNT(result)
AS Accept_percent
,100 * 
SUM(CASE WHEN Result = 'R' THEN 1 ELSE 0 END)/COUNT(result)
AS Reject_percent
FROM t
Group by Name;

或使用COUNT功能:

SELECT Name, 100 * 
COUNT(CASE WHEN Result = 'A' THEN 1 ELSE NULL END)/COUNT(result)
AS Accept_percent
,100 * 
COUNT(CASE WHEN Result = 'R' THEN 1 ELSE NULL END)/COUNT(result)
AS Reject_percent
FROM t
Group by Name;

或使用SubQuery

SELECT Name, 100 * 
(SELECT COUNT(result) FROM t WHERE result='A' And Name = main.Name)/COUNT(result)
AS Accept_percent
, 100 * 
(SELECT COUNT(result) FROM t WHERE result='R' And Name = main.Name)/COUNT(result)
AS Reject_percent 
FROM t main
Group by Name;

See this SQLFiddle

答案 1 :(得分:0)

不,没有。您必须乘以100并明确划分您的两个数字。

答案 2 :(得分:0)

尝试这样的事情:

select username, (100 * sum(case result when 'A' then 1 else 0 end) / count(*)) as accepted, 
                 (100 * sum(case result when 'R' then 1 else 0 end) / count(*)) as rejected 
    from test
    group by username