简体   繁体   中英

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.

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 .

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.

And what if the $total=0? In this scenario dividing by zero will give an error. Make sure to check it as well like:

if ($total != 0) {
$percent = $wl / $total * 100;
} else {
$percent = 0;
}

I hope you will find it helpful in the future.

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.user_id),2) as avg') );

I hope this helps.

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