douzhang1115 2017-04-19 04: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 06: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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部