0

我有一个表,它的结构如下:

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。对于 Answer 1,有两名员工投票,EmployeeId 1 和 24。对于 AnswerId 5,EmployeeId 2 也投票。

现在从这张表中,我需要根据 计算每个AnswerId人的百分比。QuestionIdEmployeeId

我怎么能解决这个问题?

4

1 回答 1

1

这就是你所追求的:

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
于 2012-07-03T12:32:21.187 回答