简体   繁体   中英

mysql group the sum(column) to maximum values but the sums must be below a given value

I have a table with columns name and amount, i want to query data that sum(amount) upto lets say 1000 in each group, in cases where a row value is greater than 1000 it can be still be displayed in its own group. i have tried this using a php loop of sum that range between 500 to 1000 but this way produces so many groups that i wish could be a voided. is there any way that we can do this in a single mysql query. regards

this is the way i crooked my way!

//this query helped me in maneuvering in provision of limits each time 
$totalLines=mysql_query("select COUNT(*) as totalRows from chasis where chasis.BL_No =xxxx order by chasis.BL_No ")or die(mysql_error());   
$fetch_totalLines=mysql_fetch_array($totalLines);
$found_rows=$fetch_totalLines['totalRows'];
$total=0;
$Toplimit=0;
$z=0;
a:
if($Toplimit>0){
$Toplimit=$Toplimit;
//$found_rows=$found_rows-$Toplimit;
$total=0;
}


$query=mysql_query("select * from chasis where chasis.BL_No =xxxx order by chasis.duty_amount limit ".$Toplimit.",".$found_rows." ")or die(mysql_error());  
$i=1;
while($row=mysql_fetch_array($query)){
$total=round($row['duty_amount'],0)+$total;
 echo'<tr>
<td>'.$i.'</td>
<td>'.$row['BL_No'].'</td>
<td>'. mb_substr($row["make"], 0, 1,"UTF8")."-";
            echo $row["model"];  
            echo'</td>
<td>'.$row['chasisNo'].'</td>
<td>'.$row['cc'].'</td>
<td>'.date("Y F", strtotime($row['year'])).'</td>
<td>'.$row['EntryNumber'].'</td>
<td>'.round($row['duty_amount'],0).'</td>
<td>&nbsp;</td>
</tr>';
if($total<=1000 and $total>=500 ){

  echo"<td colspan='8' align='right'><b>Duty Cheque for ".$i." units</b></td>
  <td><b>".$total."</b></td>
  ";
  $Toplimit=$Toplimit+$i;
  $z=$z+$i;
   goto a;
  }
  $i++;

 }

I have decided to show everything that i did may to reflect the usage of goTo statement to hold the column id I know this is a poor way to handle this but am really stuck.

你能这样尝试吗

select * from chasis where chasis.BL_No =xxxx AND chasis.duty_amount>=500 AND chasis.duty_amount<=1000 order by chasis.duty_amount

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM