咱們在實際項目中,有不少統計需求,最近就碰見一個須要,須要統計n天中的每一天的數據彙總,剛開始想的是統計前n天再減去n-1天的數據,可是這樣寫的話數據會很龐大,並且要走不少次sql sql
這樣就比較耗性能了,經過查找本身組裝了一個sql 性能
SELECT * FROM(SELECT ENTERPRISEID,SUM(CUSTOMERNUMBER)AS aaCUSTOMERNUMBER,SUM(SAVETEL)AS aaSAVETEL,SUM(FOLLOWNUMBER)AS aaFOLLOWNUMBER,SUM(FORWARDCARD)AS aaFORWARDCARD,SUM(SHOWCARD)AS aaSHOWCARD,SUM(RELIABLE) AS aaRELIABLE,(YEAR(CREATETIME)* 1000 + DAYOFYEAR(CREATETIME) DIV 1)AS groupNum FROM BEHAVIOR WHERE ENTERPRISEID = #{id} GROUP BY groupNum)AS aa ORDER BY groupNum DESC LIMIT #{cui}雖然有點長 可是更加實用。