如何在sql中获得百分比?

时间:2016-01-27 10:26:54

标签: sql tsql

[getPollResult]

@poll_form_id int

AS
BEGIN

SELECT a.question_id,a.title,COUNT(*) vote FROM tbl_poll_option a 
JOIN tbl_poll_answer b ON a.Id=b.option_id
JOIN tbl_poll_question c ON a.question_id=c.Id
WHERE poll_form_id=@poll_form_id GROUP BY a.title,a.question_id

END

我有一个民意调查系统。我使用此查询来计算每个问题的答案。  如何获得每个回答选项的百分比如下:

  

问题1 ---> option1 = 20.13%              ---> option2 = 79.87%

     

问题2 ---> option3 = 100%

     

问题3 ---> option4 = 30%              ---> option5 = 70%

     

...

1 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:

[getPollResult]

@poll_form_id int

AS
BEGIN

SELECT distinct a.question_id,a.title,COUNT(*) over(partition by a.question_id,a.title) / count(*) over(partition by a.question) as vote_percent
FROM tbl_poll_option a 
JOIN tbl_poll_answer b ON a.Id=b.option_id
JOIN tbl_poll_question c ON a.question_id=c.Id
WHERE poll_form_id=@poll_form_id

END