3

我花了一周的时间试图弄清楚这一点,它通过结合来自各种来源的东西有点工作,但还没有完全工作。

基本上我有一个订单表,我试图按客户的第一个订单日期对客户进行分组,然后显示该组到目前为止的总支出。

这是我的 SQL 查询:

SELECT DISTINCT email, billing_name,
FORMAT(SUM(total),2) AS total,
DATE_FORMAT(MIN(orderdate), '%Y-%m') AS firstorder,
DATE_FORMAT(MAX(orderdate), '%Y-%m') AS lastorder
FROM orders
GROUP BY email
ORDER BY firstorder ASC

我正在使用 PHP:

$rows = array();
while($row = mysql_fetch_array($query))
$rows[] = $row;
foreach($rows as $row) {
    $currMonth = $row['firstorder'];
    $total += $row['total'];
    if ($currMonth != $prevMonth) {
            echo $currMonth.' = $'.$total';
            $prevMonth = $currMonth;
            $total = 0;
        }
    }

这给了我一个类似的列表:

    2010-05 = $230.49
    2010-06 = $557.32
    2010-08 = $223.38

但数字不加起来,我做错了什么?以及如何显示一个小组在其他月份花费了多少?这就是我最终想要显示数据的方式,http://www.quickcohort.com/

请帮忙!谢谢!!

4

2 回答 2

0

取决于您真正追求的是什么以及您的数据是什么样的。

如果数据看起来像:

email          |BILLING NAME|Total  |OrderDate
----------------------------------------------
john@gmail.com |John Smith  |200.00 |15/05/2010
john@gmail.com |John Smith  | 15.49 |19/10/2010
john@gmail.com |Rico Swavez | 15.00 |10/08/2010
jane@gmail.com |Jane Doe    |250.00 |23/06/2010
jane@gmail.com |Jane Doe    |307.32 |27/10/2010
juan@gmail.com |Juan Valdez |223.38 |30/08/2010

然后...

SELECT email, billing_name,
FORMAT(SUM(total),2) AS total,
DATE_FORMAT(MIN(orderdate), '%Y-%m') AS firstorder,
DATE_FORMAT(MAX(orderdate), '%Y-%m') AS lastorder
FROM orders
GROUP BY email, billing_name
ORDER BY firstorder ASC

将返回

EMAIL          | BILLING NAME |TOTAL |FIRSTORDER | LASTORDER 
------------------------------------------------------------
john@gmail.com | John Smith   |215.49|2010-05    | 2010-10
jane@gmail.com | Jane Doe     |557.32|2010-06    | 2010-10
john@gmail.com | Rico Swavez  | 15.00|2010-08    | 2010-08
Juan@gmail.com | Juan Valdez  |223.38|2010-08    | 2010-08

首先在 mysql 中运行您的查询是否得到您想要的结果?如果不是,那么问题出在 SQL 上,而不是 PHP 上。如果 SQL 正在返回您想要的,那么问题出在 PHP

于 2012-04-08T01:23:35.373 回答
0

以下查询应该可以解决问题:

SELECT 
    FORMAT(SUM(z.`totalSpent`),2) AS cohortRevenueToDate, 
    z.`firstOrderMonth`,
    GROUP_CONCAT(`email`) 
FROM 
(
    SELECT 
        `email`,
        SUM(`total`) AS totalSpent, 
        DATE_FORMAT(MIN(`orderdate`), '%Y-%m') AS firstOrderMonth 
    FROM `orders`
    GROUP BY `email`
) AS z
GROUP BY z.`firstOrderMonth`
ORDER BY z.`firstOrderMonth` ASC

如果您对每个队列组成感兴趣,我已经包含了一个 GROUP_CONCAT。

于 2019-07-10T16:26:47.360 回答