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.
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.
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%.
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.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With