Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the percentage in eloquent?

please have a look at the problem. You will find it interesting. I have a table member in which I have a column result. In this result column three values can be possible and at one time only one value can be used. The value that are possible W, L and V. Forget about the V as it is not required here.

Let's say, I have 5 rows and in 3 rows I have W and in 1 row I have L and last one is V.

So here 3W and 1L out of 4(W+L together). So the percentage of W is 75%. How can I calculate it using mysql and if it is possible using eloquent would be better.

Currently, I am using this solution 1. Getting all the rows 2. Running php loop 3. And based on the value of the result column I am calculating the percentage. works fine. But I think if there are better solution why not to find it :)

Hope you have something for this problem. Thanks in advance.

like image 620
Hkm Sadek Avatar asked Dec 31 '17 08:12

Hkm Sadek


People also ask

How is percentage calculated in laravel?

In Laravel Join query with count percentage: select('marketplace. store_name', 'users.name' , **DB::raw('round((count(products. user_id)/(select count(*) from products)*100),2) as percentage')** , DB::raw('round(avg(products.

How do you find out the percentage?

Percentage can be calculated by dividing the value by the total value, and then multiplying the result by 100. The formula used to calculate percentage is: (value/total value)×100%.

How do I calculate a percentage in Matplotlib?

To calculate a percentage in Python, use the division operator (/) to get the quotient from two numbers and then multiply this quotient by 100 using the multiplication operator (*) to get the percentage.


2 Answers

If you want a pure Eloquent solution, do this:

$wl = Member::whereIn('result', ['W', 'L'])->count();
$total = Member::count();
$percent = $wl / $total * 100;

This will be much more efficient than actually retrieving any records from DB.

like image 72
Alexey Mezenin Avatar answered Oct 19 '22 06:10

Alexey Mezenin


Your question is a bit vague, but from what I see the COUNT function should be sufficient here:

SELECT
    100.0 * COUNT(W) / COUNT(*) AS w_pct,
    100.0 * COUNT(L) / COUNT(*) AS l_pct
FROM yourTable;

Of course, if you are already doing an aggregation then we can modify the above query to include GROUP BY.

like image 6
Tim Biegeleisen Avatar answered Oct 19 '22 07:10

Tim Biegeleisen