小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

如何給SQL查詢添加合計(jì)行(1)

 mybook564 2013-09-24

SQL查詢是SQL數(shù)據(jù)庫的核心功能,下面為您介紹給SQL查詢添加合計(jì)行的方法示例,供您參考,希望對(duì)您學(xué)習(xí)SQL查詢能有所幫助。

.數(shù)據(jù)表t_test
id      銷售人員id         商品id           數(shù)量

id       emp_id            product_id       qty

1        01                     001               200

2        01                     002               300

2        01                     002               400

3        02                      001              400

4        02                      002              500
 

  1. Create table #t_test(  
  2. id int not null,  
  3. emp_id int not null,  
  4. product_id int not null,  
  5. qty int not null  
  6. )  
  7. insert into #t_test values(1,01,001,200)  
  8. insert into #t_test values(2,01,002,300)  
  9. insert into #t_test values(3,01,002,400)  
  10. insert into #t_test values(4,02,001,400)  
  11. insert into #t_test values(5,02,002,500)  
  12.  
  13. select *   
  14. from #t_test 


2.需要得到的結(jié)果

需要得到類似下面的結(jié)果

--------------------------------------

emp_id                    qty

01                           900

02                           900

合計(jì)                        1800

--------------------------------------

大家看到了,這里加上了一個(gè)合計(jì)列

參考sql語句如下

  1. -- for MS SQL Server 2005  
  2. select isnull(CONVERT(varchar(20), emp_id),'Total') as 'emp_id'   
  3.     ,sum(qty) as 'qty_Total'  
  4. from #t_test  
  5. group by emp_id  
  6. with rollup 

SQL查詢的結(jié)果如下所示

emp_id qty_Total

1 900
2 900
Total 1800


3.負(fù)責(zé)一點(diǎn),統(tǒng)計(jì)每個(gè)銷售人員以及商品的數(shù)量

--------------------------------------

emp_id         product_id             qty

01                 001                        200

01                  001                       700

01                  小計(jì)                      900

02                 001                          400

02                 002                          500

02                 小計(jì)                         900

合計(jì)                                            1800

--------------------------------------

由于要統(tǒng)計(jì)合計(jì)以及小計(jì),不能簡(jiǎn)單的用nvl來產(chǎn)生"合計(jì)"了,要用grouping函數(shù),來判斷者某行是否有rollup產(chǎn)生的合計(jì)行,

  1. select  
  2.  
  3. case when grouping(emp_id)=1 and grouping(product_id)=1 then '合計(jì)' else emp_id end emp_id,  
  4.  
  5. case when grouping(emp_id)=0 and grouping(product_id)=1 then '小計(jì)' else procudt_id end product_id,  
  6.  
  7. sum(qty) qty  
  8.  
  9. from t_test  
  10.  
  11. group by rollup(emp_id,product_id)  
  12.  

注意,grouping(emp_id)=1,說明是有rollup函數(shù)生成的行,0為數(shù)據(jù)庫本身有的行。

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多