使用MYSQL/PHP显示从现在到x天前的每日总计

使用MYSQL/PHP显示从现在到x天前的每日总计,php,mysql,database,Php,Mysql,Database,我有一张名为“订单”的表格,其中包含:;id、订单总数和时间字段。”“时间”是一个整数,存储unix时间戳 命令 | id | order_total | time | ------------------------------------- | 1 | 42.00 | 1443355834 | | 2 | 13.00 | 1443460326 | | 3 | 51.00 | 1443468094 | | 4

我有一张名为“订单”的表格,其中包含:;id、订单总数和时间字段。”“时间”是一个整数,存储unix时间戳

命令

| id | order_total | time | ------------------------------------- | 1 | 42.00 | 1443355834 | | 2 | 13.00 | 1443460326 | | 3 | 51.00 | 1443468094 | | 4 | 16.00 | 1443477442 | | 5 | 10.00 | 1443606966 | | 6 | 53.00 | 1443608256 | 我希望能够使用php在表格中显示前几天、几周或几个月内每天“订单总数”的总和,因此它将如下所示:

| Date | Order Total | --------------------------- | 27/09/15 | 42.00 | | 28/09/15 | 80.00 | | 30/09/15 | 63.00 | 我已经做了一个MYSQL查询和一个php循环,这样做很有效,但是作为MYSQL的新手,我可能过于复杂了,必须有一个更简单的方法来实现这一点吗?当我说“工作种类”时,它将正确地求和并显示截止到当天的订单总数,但由于某种原因,它会将当天与前一天合并

以下是我目前拥有的:

$x = $interval;
$y = $x - 1;

while ($x > 0) {
    $sql10 = "
        SELECT id,
               time,
               SUM(order_total) as sum,
               date_format(DATE_SUB(FROM_UNIXTIME($now_time), INTERVAL $x DAY), '%Y-%m-%d') as thedate  
         FROM $ordersTABLE 
        WHERE FROM_UNIXTIME(time) BETWEEN date_format(DATE_SUB(FROM_UNIXTIME($now_time), INTERVAL $x DAY),'%Y-%m-%d') 
          AND date_format(DATE_SUB(FROM_UNIXTIME($now_time), INTERVAL $y DAY),'%Y-%m-%d')";

    $result10 = mysql_query ( $sql10, $cid ) or die ( "Couldn't execute query." );

    while ( $row = mysql_fetch_array ( $result10) ) {
        $order_total = $row ["order_total"];
        $thedate = $row ["thedate"];
        $sum = $row ["sum"];
        $sum = number_format($sum,2);
        $thedate = strtotime($thedate);
        $thedate = date("d/m/y",$thedate);

        print "<tr><td width=\"120\">$thedate</td><td>\$$sum</td></tr>";
    }

    $x--;
    $y--;
}
字符串$now_time包含当前时间作为Unix时间戳,因此无法更改转换为系统时间,这包含用户正确的本地时间


有更好的方法吗?

您可以使用函数将时间戳转换为YYYY-MM-DD,然后仅选择由于该函数而足够旧的时间戳。今天的日期由函数提供

首先,该查询检索早于时间间隔的订单的总计,并重新设置日期字段的格式:

$q1 = "SELECT " . $ordersTABLE . ".order_total AS total, FROM_UNIXTIME(" . $ordersTABLE . ".time, '%Y-%m-%d') AS short_date FROM " . $ordersTABLE . " WHERE DATEDIFF(CURDATE(), short_date) > " . $intervalInDAYS;
然后,将一天的总数加起来:

$q2 = "SELECT short_date AS day, SUM(total) AS total FROM (" . $q1 . ") GROUP BY short_date";
然后执行存储在$q2中的查询以及显示结果所需的所有其他操作。 查询结果的格式应为:

|    day    |    total    |
===========================
| 25/09/15  |  34.00      |
| 16/09/15  | 100.00      |
| 31/07/14  |   3.20      |
|    ...    |     ...     |

试试这个,你是什么意思,什么样的作品?它起作用了,还是不起作用了?公平的警告,如果您的代码符合您的规范/要求,那么堆栈溢出通常是离题的。