简体   繁体   中英

Mysql Calculate Percentage Of Selected Rows

I'm sorry if my question irrelevant. Because I'm not expert of mysql.

I have surveys in my website. If someone votes my survey, i want to show survey results to the voter.

Here is the DB Structure;

surveys Table (Includes Survey Name Description and survey_id )

调查

survey_choices Table (Includes Survey Chocies and related with survey_id to Surveys Table)

调查选择

I'm trying to calculate only visible survey choices %percentage.

If i have only 1 survey, it's calculating correct results. But if i have more than 1 survey, mysql calculating whole survey_vote_count values of all table.

Here is my MySQL query;

SELECT 
survey_vote_id, survey_vote_name, survey_vote_count, survey_id, 
survey_vote_count * 100 / t.s AS survey_percentage
FROM survey_votes
CROSS JOIN (SELECT SUM(survey_vote_count) AS s FROM survey_votes) t
WHERE visibility = :visibility
AND survey_id = :surveyId
ORDER BY `survey_votes`.`order_id` ASC

How can i calculate for eg only survey_id = 1 and visibility = 1 %percentage = %100?

Any help will greatly appricated.

You should add the same condition to your cross join. At the moment, in your select you sum all survey_vote_count without the same where condition (visibility and survey_id.

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