我有一個表的命令是這樣的:像這樣累積計數隨着時間的推移
customer_id order_date
10 2012-01-01
11 2012-01-02
10 2012-01-02
12 2012-01-03
11 2012-01-04
12 2012-02-01
11 2012-02-04
13 2012-02-05
14 2012-02-06
我怎樣才能得到一個累計平均隨着時間的推移(每月):
order date count orders count customers (customer_id)
2012-01 1 1 (12)
2012-01 2 2 (10,11)
2012-02 1 2 (13,14)
2012-02 2 2 (10,12
2012-02 3 2 (11)
展示瞭如何的數客戶與每個客戶的訂單數量隨時間發展。
下面的查詢給我想要的信息 - 但不是隨着時間的推移。我如何隨時間迭代查詢?
SELECT number_of_orders, count(*) as amount FROM (
SELECT o.customer_id, count(*) as number_of_orders
FROM orders o
GROUP BY o.customer_id) as t1
GROUP BY number_of_orders
更新:
現在已經建立了下面的PHP代碼生成我需要什麼,不知道這是否可以使用累積計數像http://www.freeopenbook.com/mysqlcookbook/mysqlckbk-chp-12-sect-14.html
$year = 2011;
for ($cnt_months = 1; $cnt_months <= 12; $cnt_months++) {
$cnt_months_str = ($cnt_months < 10) ? '0'.$cnt_months : $cnt_months;
$raw_query = "SELECT number_of_orders, count(*) as amount
FROM (
SELECT
o.customer_id,
count(*) as number_of_orders
FROM orders o
where Date_Format(o.order_date, '%Y%m') >= " . $year . "01 and Date_Format(o.order_date, '%Y%m') <= " . $year . $cnt_months_str . "
GROUP BY o.customer_id) as t1
GROUP BY number_of_orders";
$query = db_query($raw_query);
while ($row = db_fetch_array($query)) {
$data[$cnt_months_str][$row['number_of_orders']] = array($row['number_of_orders'], (int)$row['amount']);
}
}
感謝您的想法!但它不會產生我正在尋找的那種數據。如上所述添加了PHP/mysql解決方法。不過,我想有一種更優雅的方式只使用SQL解決這個問題? – Cord 2012-02-21 12:44:41
輸出有什麼問題?這應該產生你所要求的 - 不能幫助,如果你不讓我知道它如何不按預期工作:) – 2012-02-21 12:48:22
嗨西蒙,查詢按天分組,而不是按月。已經添加了一個有效的PHP解決方法,但是在一個查詢中使用它會很好。再次感謝! – Cord 2012-02-21 20:43:22