-- 統計購買次數最大和最小 select max(times) from 統計表 where effective = '有效' -- 統計最大購買次數間隔、最小間隔以及平均間隔(中位數的話,因爲MySQL沒有中位數函數,因此能夠利用子查詢的SQL經過程序代碼計算) SELECT max(date) as max, min(date) as min, sum( date * mans ) / count( mans ) as avg FROM ( SELECT ifnull(datediff( a.order_time, ( SELECT order_time FROM 統計表 WHERE times = 次數1 AND effective = '有效' AND a.fans_id = fans_id ) ),0) AS date, a.fans_id, 1 AS mans FROM 統計表 a WHERE a.times = 次數2 AND effective = '有效' ) t
UPDATE (SELECT @rownum:=@rownum+1 as rn,id,fans_id,order_time from (SELECT id,fans_id,order_time from 統計表 where fans_id = 購買人 and effective = '有效' ORDER BY order_time asc) h, (SELECT @rownum:=0) t) t1, statistics_repurchase t2 set t2.times=t1.rn where t2.id=t1.id;
初版SQL以下:mysql
SELECT a.fans_id, a.order_time, a.sync_time, count( * ) AS times FROM 統計表 AS a, 統計表 AS b WHERE a.fans_id = b.fans_id AND a.order_time >= b.order_time AND a.effective = '有效' AND b.effective = '有效' AND a.series LIKE concat('%','系列','%') AND b.series LIKE concat('%','系列','%') GROUP BY a.fans_id, a.id -- 按照購買人id,按照購買時間進行排序,並標記序號,加上建立表語句以下(建表時需加索引,方便後續查找): CREATE TABLE 臨時表名 ( id INT PRIMARY KEY AUTO_INCREMENT, fans_id VARCHAR ( 32 ), order_time datetime, sync_time date, times INT ( 6 ), PRIMARY KEY ( id ), INDEX mid_fans_id ( fans_id ) USING BTREE, INDEX mid_order_time ( order_time ) USING BTREE, INDEX mid_times ( times ) USING BTREE, INDEX mid_sync_time ( sync_time ) USING BTREE ) AS ( SELECT a.fans_id, a.order_time, a.sync_time, count( * ) AS times FROM 統計表 AS a, 統計表 AS b WHERE a.fans_id = b.fans_id AND a.order_time >= b.order_time AND a.effective = '有效' AND b.effective = '有效' AND a.series LIKE concat('%','系列','%') AND b.series LIKE concat('%','系列','%') GROUP BY a.fans_id, a.id ); -- 因爲數據庫版本爲5.4,因此建完臨時表不支持一條sql屢次查詢,沒辦法,只能直接建立表
SELECT a.fans_id, a.order_time, a.sync_time, ( @i := CASE WHEN @pre_keyword = fans_id THEN @i + 1 ELSE 1 END ) AS times, @pre_keyword:=fans_id FROM ( SELECT fans_id, order_time, sync_time FROM 統計表 WHERE effective = '有效' AND series LIKE concat('%','系列','%') ORDER BY fans_id,order_time ) a, ( SELECT @i := 0, @pre_keyword := '' ) AS b