mysql总和在flot图表中输出

时间:2013-11-26 08:02:11

标签: mysql sql flot

我试图在flot / jquery图表上输出两个表项的运行总数与日期。

到目前为止,代码可以在给定日期输出两个值的折线图,但我试图显示同一图表上每列的运行总计。 不确定是否可以使用单个mysql查询使用SUM(值)来实现这个? - 只是无法让它工作。

<?php

$query=("SELECT hours, credits, entryDate FROM entry WHERE uid='1'");

$result = mysql_query($query);        

while($row = mysql_fetch_assoc($result))
{
    $credits[] = array ( strtotime ($row['entryDate'])*1000,($row['credits']));
    $hours[] = array ( strtotime ($row['entryDate'])*1000,($row['hours']));
} ?>

</script>
var credits = <?php echo json_encode($credits);?>
var hours = <?php echo json_encode($hours);?>

1 个答案:

答案 0 :(得分:2)

最简单的方法就是在php中保持一个运行总计,并为每个日期添加: -

<?php

$query=("SELECT hours, credits, entryDate FROM entry WHERE uid='1' ORDER BY entryDate");

$result = mysql_query($query);        

while($row = mysql_fetch_assoc($result))
{
    $runningtotalcredits += $row['credits'];
    $runningtotalhours += $row['hours'];
    $credits[] = array ( strtotime ($row['entryDate'])*1000,$row['credits']);
    $creditssofar[] = array ( strtotime ($row['entryDate'])*1000,$runningtotalcredits);
    $hours[] = array ( strtotime ($row['entryDate'])*1000,$row['hours']);
    $hourssofar[] = array ( strtotime ($row['entryDate'])*1000,$runningtotalhours);
} ?>

</script>
var credits = <?php echo json_encode($credits);?>
var hours = <?php echo json_encode($hours);?>
var creditssofar = <?php echo json_encode($creditssofar);?>
var hourssofar = <?php echo json_encode($hourssofar);?>

也应该可以使用相关的子查询在SQL中执行它,但效率可能不是很好: -

<?php

$query=("SELECT hours, 
                credits, 
                entryDate, 
                (SELECT SUM(hours) AS hourssofar FROM entry b WHERE uid='1' AND b.entryDate <= a.entryDate),
                (SELECT SUM(credits) AS creditssofar FROM entry c WHERE uid='1' AND c.entryDate <= a.entryDate)
        FROM entry a
        WHERE uid='1' 
        ORDER BY entryDate");

$result = mysql_query($query);        

while($row = mysql_fetch_assoc($result))
{
    $credits[] = array ( strtotime ($row['entryDate'])*1000,$row['credits']);
    $creditssofar[] = array ( strtotime ($row['entryDate'])*1000,$row['creditssofar']);
    $hours[] = array ( strtotime ($row['entryDate'])*1000,$row['hours']);
    $hourssofar[] = array ( strtotime ($row['entryDate'])*1000,$row['hourssofar']);
} ?>

</script>
var credits = <?php echo json_encode($credits);?>
var hours = <?php echo json_encode($hours);?>
var creditssofar = <?php echo json_encode($creditssofar);?>
var hourssofar = <?php echo json_encode($hourssofar);?>

(未经测试)