2012-08-30 30 views
0

我面临一个问题,写一个SQL查询以获得结果在%模式下,我很熟悉SUM()COUNT() SQL Server的功能,但面临问题来实现逻辑内查询我想导致以下表格: -是否有任何内置函数来计算在SQL Server中的百分比

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中的百分比?

回答

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

0

不,没有。你将不得不乘以100并明确地划分你的两个数字。

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