I'm currently working on feedback system where the user can give feedback, In my case, I have to count percentage for each option like the question has many options I should show the percentage for each option, For example, how many people selected option a,b,c,d so on.
My Answers table
user_id question_id option(selected by user)
1 1 2
2 1 1
3 1 4
4 1 3
Now what I want to achieve is
question1
option1(25% people selected option1)
option2(25% people selected option2)
option3(25% people selected option3)
option4(25% people selected option4)
What should be the query for above output,Can any one help on that please.
Try this one,
You will get percentage of each option for question with question_id = 1
DB::table('answers')->where('question_id',1)
->select('option',DB::raw('count(*) *100 / (select count(*) from answers) as count'))
->groupBy('option')
->get();