0

我在编写 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 中计算百分比的内置函数?

4

3 回答 3

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;

看到这个 SQLFiddle

于 2012-08-30T10:58:19.900 回答
0

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

于 2012-08-30T10:56:16.760 回答
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
于 2012-08-30T11:01:51.403 回答