How to calculate percentage in laravel

I am currently working on a feedback system where the user can give feedback. In my case, I have to calculate the percentages for each parameter, since the question has many options. I have to show the percentage for each parameter. For example, how many people have chosen option a, b, c, d, and so on.

Table "My Answers"

     user_id         question_id      option(selected by user)
     1                       1                             2
     2                       1                             1
     3                       1                             4
     4                       1                             3

      

Now I want to reach

  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 request for the output above, can anyone help with this.

+3


source to share


1 answer


Try it,

You will get the percentage of each option for the 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();

      

+1


source







All Articles