Home All Groups Group Topic Archive Search About
Author
1 Dec 2005 7:09 PM
fniles
We have a Result table with fields called QuestionID and Answer.
How can I get a query result where the result is group by the answer and its
percentage ?
Thanks.

For ex: Results table:
QuestionID    Answer
1                    aaa
1                    aaa
1                    ddd
2                    yyyy

I want the result of the query for QuestionID = 1 to look like:
aaa    2    66.6666
ddd    1    33.3333

CREATE PROCEDURE GetResults
@QuestionID numeric(9)
AS

SELECT     Answer, COUNT(Answer) AS votes
FROM         Results
WHERE     (Question = @QuestionID)
GROUP BY Answer
GO

Author
1 Dec 2005 7:21 PM
Razvan Socol
Hello, fniles

Use something like this:

SELECT Answer,
    COUNT(*) AS votes,
    100. * COUNT(*) / (
        SELECT COUNT(*)
        FROM Results
        WHERE QuestionID = @QuestionID
    ) as Percentage
FROM Results
WHERE QuestionID = @QuestionID
GROUP BY Answer

Razvan
Author
1 Dec 2005 7:30 PM
fniles
Thanks ! That works.

Show quote
"Razvan Socol" <rso***@gmail.com> wrote in message
news:1133464892.892475.83390@z14g2000cwz.googlegroups.com...
> Hello, fniles
>
> Use something like this:
>
> SELECT Answer,
> COUNT(*) AS votes,
> 100. * COUNT(*) / (
> SELECT COUNT(*)
> FROM Results
> WHERE QuestionID = @QuestionID
> ) as Percentage
> FROM Results
> WHERE QuestionID = @QuestionID
> GROUP BY Answer
>
> Razvan
>

AddThis Social Bookmark Button