1

我有一个具有这种结构的表:

table name: customer_history

id| orders | order_date (timestamp) |  status    |  
--------------------------------------------------
 1|   1    | 2012-05-29 13:11:59    |  active    |
 2|   1    | 2012-05-29 13:11:59    |  active    |
 3|   1    | 2012-05-30 13:11:59    |  canceled  |
 4|   1    | 2012-05-31 13:11:59    |  trialing  |

我需要查询数据库并计算总订单数,其中状态!= 取消,每一天,回到一个日历月,并为每个每日总数分配一个唯一变量。

昨天的订单总额将类似于 $day-1、两天前 $day-2 等。

编辑下面的答案。

$query = "SELECT 
            COUNT(*) AS number, 
            DATE(order_date) AS order_day 
        FROM 
            customer_history
        WHERE 
            status <> 'canceled' 
        GROUP BY 
            order_day 
        ORDER BY 
            order_date 
        DESC
        LIMIT 31";

$result = mysql_query($query) or die(mysql_error());

$i = 1;
$days = array();

while($row = mysql_fetch_assoc($result)) {

      $days[$i] = $row;
      $i++;
}

echo $days[1]['number'];
echo $days[2]['number'];
echo $days[3]['number'];
echo $days[4]['number'];
echo $days[5]['number'];
echo $days[6]['number'];
4

2 回答 2

1
SELECT COUNT(*) AS number, DATE(order_date) AS order_day FROM orders WHERE status <> 'canceled' GROUP BY order_day ORDER BY order_date DESC LIMIT 31

然后循环遍历结果。第一个是当天,第二个是昨天,第三个是前天,以此类推。

编辑

包括循环/变量:

    <?php

$query = "SELECT 
                COUNT(*) AS number, 
                DATE(order_date) AS order_day 
            FROM 
                orders 
            WHERE 
                status <> 'canceled' 
            GROUP BY 
                order_day 
            ORDER BY 
                order_date 
            DESC
            LIMIT 31";

    $result = mysql_query($query);

    $i = 1;
    $days = array();

    while($row = mysql_fetch_assoc($query)
    {
        $days[$i] = $row;
        $i++;

    }

    ?>

echo $days[1]['number'] 为您提供今天的订单数量,$days[2]['number'] 为昨天等。您可以通过 echo $days[x][' 输出实际日期order_day']。

于 2012-06-09T19:29:15.047 回答
1

试试这个查询GROUP BY order_date

SELECT COUNT(*) AS number, DATE(order_date) AS order_day
FROM orders WHERE status != 'canceled' 
GROUP BY order_date ORDER BY order_date DESC
于 2012-06-09T19:32:55.123 回答