douzhang1115 2017-04-19 12:08
浏览 27
已采纳

根据MySQL PHP中该行的列值,按比例将数字除以每一行

I'm trying to distribute an amount proportionately to each row of a table based on the value of a column, 'value' and it's percentage of the sum of that column for all rows. For example

AmounttoDistribute = 200
CurrentTotal = 100
Row 1 value = 25
Row 2 Value = 50
Row 3 Value = 15
Row 4 Value = 10

I want to make it where

Row 1 will receive 50
Row 2 will receive 100
Row 3 will receive 30 
Row 4 will receive 20

I've tried a couple different while loops but so far the results are very different than what I'm trying to achieve. I've already got the $AmounttoDistribute and $SumofValue in variables which I know to be correct. Here's what I've tried:

$val = mysqli_query($db, "SELECT Value FROM Table WHERE columnX = 1 AND columnY = 1");
$Result = mysqli_fetch_array($val);
$value = $Result['Value'];

while($Result = mysqli_fetch_array($val)){ 
mysqli_query($db, "UPDATE Table SET Value = Value + (Value / $SumofValue * $AmounttoDistribute) WHERE columnX = 1 AND columnY = 1");     

I've also tried the while loop below where I already have a variable for AmounttoDistribute divided by SumofValue, ($AmountPerEach1):

$val = mysqli_query($db, "SELECT Value FROM Table WHERE columnX = 1 AND columnY = 1");
$Result = mysqli_fetch_array($val);
$value = $Result['Value'];

while($Result = mysqli_fetch_array($val)){ 
mysqli_query($db, "UPDATE Table SET Value = Value + (Value * $AmountPerEach1) WHERE columnX = 1 AND columnY = 1"); 

Thanks for any help

  • 写回答

1条回答 默认 最新

  • douyicao2199 2017-04-19 14:23
    关注

    If you know the AmountToDistribute and CurrentTotal, you can do this via one simple SQL statement.

    Basically:

    UPDATE table SET column = column + ((AmountToDistribute/CurrentTotal)*column);
    

    Specifically for this case:

    UPDATE Table SET Value = Value + 2*Value;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?