日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
如何給SQL查詢添加合計行

SQL查詢是SQL數(shù)據(jù)庫的核心功能,下面為您介紹給SQL查詢添加合計行的方法示例,供您參考,希望對您學(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. select * 
  13. from #t_test

#p#

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

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

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

emp_id                    qty

01                           900

02                           900

合計                        1800

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

大家看到了,這里加上了一個合計列

參考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#p#

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

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

emp_id         product_id             qty

01                 001                        200

01                  001                       700

01                  小計                      900

02                 001                          400

02                 002                          500

02                 小計                         900

合計                                            1800

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

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

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

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


當(dāng)前文章:如何給SQL查詢添加合計行
分享網(wǎng)址:http://www.5511xx.com/article/dhscipc.html