找到百分比值

时间:2012-07-03 12:04:34

标签: sql sql-server-2008 tsql sql-server-2008-r2

我有一张桌子,其结构如下:

VoteId  QuestionId  AnswerId    EmployeeId

6        1              5              2
7        1              1              1
10       2              6              1
12       1              1             24

这里为QuestionId 1,我们有2个答案。 AnswerId 1和5.对于答案1,两名员工已投票,EmployeeId 1和24.另外,对于AnswerId 5,EmployeeId 2已投票。

现在,从此表中我需要根据AnswerId计算单个QuestionId的每个EmployeeId的百分比。

我怎么解决这个问题?

1 个答案:

答案 0 :(得分:0)

这就是你所追求的:

DECLARE @t TABLE (VoteId  INT,QuestionId  INT,AnswerId    INT,EmployeeId INT)
INSERT @t VALUES 
(6,   1,    5,   2),
(7,   1,    1,    1),
(10,  2,    6,    1),
(12,  1,    1,   24)

SELECT  QuestionId, 
        COUNT(*) * 100.0 / (SELECT COUNT(*) FROM @t)
        AS PercentageOfVotesReceived
FROM    @t
GROUP   BY QuestionId

SELECT  AnswerId, 
        COUNT(*) * 100.0 / (SELECT COUNT(*) FROM @t)
        AS PercentageOfVotesReceived
FROM    @t
GROUP   BY AnswerId 

SELECT  EmployeeId, 
        COUNT(*) * 100.0 / (SELECT COUNT(*) FROM @t)
        AS PercentageOfVotesReceived
FROM    @t
GROUP   BY EmployeeId