输入代码这里花了一个星期试图解决这个问题,通过组合来自不同来源的东西,但尚未正常工作,它有点工作。
我基本上有一个订单表,我试图按照他们的第一个订单日期对客户进行分组,并显示该组到目前为止的总支出
这是我的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/
请帮忙!谢谢!
答案 0 :(得分: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
中答案 1 :(得分: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。