简体   繁体   中英

How can I get percentage in sql?

[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

I have a poll system. I use this query to get count of every answer of question. How can I get percentage of every answered option like this:

question 1 ---> option1=20.13 % ---> option2=79.87 %

question 2 ---> option3=100 %

question 3 ---> option4=30 % ---> option5=70 %

....

You can try following:

[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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM