[英]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
. 我有一个表member
,其中有一个列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
. 可能的值W
, L
和V
Forget about the V
as it is not required here. 忘记V
因为这里不需要。
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
. 假设我有5行,在3行中有W
,在1行中有L
,最后一个是V
So here 3W and 1L out of 4(W+L together). 所以这里3W和1L占4(W + L在一起)。 So the percentage of W is 75%. 因此W的百分比为75%。 How can I calculate it using mysql and if it is possible using eloquent would be better. 我该如何使用mysql计算它,如果可以使用雄辩,那会更好。
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. 当前,我正在使用此解决方案1.获取所有行2.运行php循环3.然后根据结果列的值计算百分比。 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: 您的问题有点含糊,但是从我看来, COUNT
函数在这里应该足够了:
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
. 当然,如果您已经在进行聚合,则可以修改上面的查询以包括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? 如果$ 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: 在Laravel Join查询中,具有计数百分比:
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. 我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.