溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

mysql如何實(shí)現(xiàn)每隔N行生成一個(gè)匯總行

發(fā)布時(shí)間:2021-11-08 09:15:15 來源:億速云 閱讀:308 作者:小新 欄目:MySQL數(shù)據(jù)庫

小編給大家分享一下mysql如何實(shí)現(xiàn)每隔N行生成一個(gè)匯總行,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!



處理這種每隔N行生成一個(gè)匯總行的需求,一共有三種方式


  • select when c is null then '匯總' else '' end s,ifnull(c,sumc) c from (  

  •     select ceil(id/3) l,c,null sumc  

  •     from   

  •     (  

  •         select @id:=@id+1 id, t1.* from t t1,(select @id:=0) vars    

  •     ) t2  

  •     union all    

  •     select ceil(id/3) l,null,from   

  •     (  

  •         select @id1:=@id1+1 id, t1.* from t t1,(select @id1:=0) vars    

  •     ) t3  

  •     group by l  

  • ) t order by l,ifnull(c,'9999'); 


  • 結(jié)果:


  • mysql如何實(shí)現(xiàn)每隔N行生成一個(gè)匯總行

  • 第二招,數(shù)字輔助表補(bǔ)全. 性能較好. 計(jì)算匯總行,理解稍微復(fù)雜.



  • 先增加一個(gè)數(shù)字輔助表 nums


    1. table(int null)delimiter $$

    2.  procedure pCreateNumscnt )

    3.     declare s default;

    4. truncate  nums    while s=        intoselect;

    5. set=+;

    6. end;

    7.  $$

    8. ;


    9. create(intbegin

    10. int  1    table;

    11. insert  nums  s    while s2=        intoselect+from;

    12. set=*;

    13. end;

    14.  $$

    15. ;


  • 初始化數(shù)字輔助表


  • select s,ifnull(c,cc) c  

  • from (    

  •     select     

  •     when rn is null then '匯總' else '' end s,     

  •     t4.c,  

  •     if(mod(t3.id,4)!=0 ,when @total=-1 then @total:=t4.c else @total:=@total+t4.c end,@total) cc,  

  •     when mod(t3.id,4)=0 then @total:=-1 else null end     

  •     from (    

  •         select * from nums where id<=    

  •         (select (ceil(from t )    

  •     ) t3    

  •     join (    

  •         select     

  •         when mod(@rn+1,4)=0 then @rn:=@rn+2 else @rn:=@rn+1 end rn ,    

  •         t1.* from t t1,(select @rn:=0,@total:=0) vars      

  •     ) t4 on(t3.id=t4.rn)    

  • ) result;    


  • 這個(gè)理解稍微有點(diǎn)復(fù)雜,


  • 第二招改進(jìn)版本


    1. select when id is null then '匯總' else '' end s,from (  

    2.     select @id:=@id+1 id, t1.* from t t1,(select @id:=0) vars      

    3. ) t2  

    4. group by ceil(t2.id/3),t2.id with rollup;  



以上是“mysql如何實(shí)現(xiàn)每隔N行生成一個(gè)匯總行”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI