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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!