小編給大家分享一下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é)果:

第二招,數(shù)字輔助表補(bǔ)全. 性能較好. 計(jì)算匯總行,理解稍微復(fù)雜.
先增加一個(gè)數(shù)字輔助表 nums
table(int null)delimiter $$
procedure pCreateNumscnt )
declare s default;
truncate nums while s= intoselect;
set=+;
end;
$$
;
create(intbegin
int 1 table;
insert nums s while s2= intoselect+from;
set=*;
end;
$$
;
初始化數(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)版本
select when id is null then '匯總' else '' end s,from (
select @id:=@id+1 id, t1.* from t t1,(select @id:=0) vars
) t2
group by ceil(t2.id/3),t2.id with rollup;
以上是“mysql如何實(shí)現(xiàn)每隔N行生成一個(gè)匯總行”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)-成都網(wǎng)站建設(shè)公司行業(yè)資訊頻道!
本文名稱:mysql如何實(shí)現(xiàn)每隔N行生成一個(gè)匯總行-創(chuàng)新互聯(lián)
地址分享:http://chinadenli.net/article30/eoipo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供營(yíng)銷型網(wǎng)站建設(shè)、響應(yīng)式網(wǎng)站、定制開(kāi)發(fā)、Google、網(wǎng)站制作、用戶體驗(yàn)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容