获得总价值直到当月?

时间:2014-11-18 09:29:18

标签: php mysql

我已使用下面的查询成功获取数据。

$sql2 = "Select element,
SUM(CASE WHEN Month = 'Jan' THEN total ELSE 0 END ) AS Jan,
SUM(CASE WHEN Month = 'Feb' THEN total ELSE 0 END ) AS Feb,
SUM(CASE WHEN Month = 'Mac' THEN total ELSE 0 END ) AS Mac //until december
from tbl_macscstate
group by element";
$rs2 = mysql_query($sql2);
$getRec2 = mysql_fetch_assoc($rs2);

现在,我的问题是我想从7月到现在的月份增加价值,我不知道该怎么做。有人能指出我正确的方向。下面的代码是我如何在表格中显示数据。

<?php while ($row = mysql_fetch_assoc($rs2)) {?>
<tr>
    <td><?php echo $row['element']; ?></div></td>   
    <?php if( $year != '2014' ){ ?>
    <?php if( 1 <= $monthID ): ?><td><?php echo $row['Jan']; ?></td><?php endif; ?>
    <?php if( 2 <= $monthID ): ?><td><?php echo $row['Feb']; ?></td><?php endif; ?>
    <?php if( 3 <= $monthID ): ?><td><?php echo $row['Mac']; ?></td><?php endif; ?>
    <?php if( 4 <= $monthID ): ?><td><?php echo $row['Apr']; ?></td><?php endif; ?>
    <?php if( 5 <= $monthID ): ?><td><?php echo $row['May']; ?></td><?php endif; ?>
    <?php if( 6 <= $monthID ): ?><td><?php echo $row['Jun']; ?></div></td><?php endif; ?>
    <?php } ?>
    <?php if( 7 <= $monthID ): ?><td><?php echo $row['Jul']; ?></td><?php endif; ?>
    <?php if( 8 <= $monthID ): ?><td><?php echo $row['Aug']; ?></td><?php endif; ?> //until Dec
    <td><div align="center" style="color:black"><?php //echo YTD; ?></td>   
</tr>                                  

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题,这个功能就可以完成这个任务:

<?php    
    function getSumBetweenMonths($month1,$month2,$row)
    {           
        $m2i=array('Jan'=>1,'Feb'=>2,'Mar'=>3,'Apr'=>4,'May'=>5,'Jun'=>6,'Jul'=>7,'Aug'=>8,'Sep'=>9,'Oct'=>10,'Nov'=>11,'Dec'=>12);
        $i2m=array(1=>'Jan',2=>'Feb',3=>'Mar',4=>'Apr',5=>'May',6=>'Jun',7=>'Jul',8=>'Aug',9=>'Sep',10=>'Oct',11=>'Nov',12=>'Dec');
        $sum=0;
        $i=$m2i[$month1];
        $j=$m2i[$month2];
        if(!$i||!$j)Die("Unknown months $month1,$month2");
        for(;;)
        {
            $sum+=$row[$i2m[$i]];
            if($i==$j) return $sum;
            $i++;
            if($i>=13) $i=1;
        }
    }

    echo getSumBetweenMonths('Jul',date('M'),$row);  
?>