日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

SQL:给查询添加一个合计行

發布時間:2024/4/17 数据库 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SQL:给查询添加一个合计行 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
.數據表t_test

id????? 銷售人員id???????? 商品id?????????? 數量

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

?

Create?table?#t_test(
id?
int?not?null,
emp_id?
int?not?null,
product_id?
int?not?null,
qty?
int?not?null
)
insert?into?#t_test?values(1,01,001,200)
insert?into?#t_test?values(2,01,002,300)
insert?into?#t_test?values(3,01,002,400)
insert?into?#t_test?values(4,02,001,400)
insert?into?#t_test?values(5,02,002,500)

select?*?
from?#t_test

?

?

?

2.需要得到的結果

需要得到類似下面的結果

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

emp_id??????????????????? qty

01?????????????????????????? 900

02?????????????????????????? 900

合計??????????????????????? 1800

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

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

參考sql語句如下

?

--?for?MS?SQL?Server?2005
select?isnull(CONVERT(varchar(20),?emp_id),'Total')?as?'emp_id'?
????,
sum(qty)?as?'qty_Total'
from?#t_test
group?by?emp_id
with?rollup

?

查詢的結果如下所示

emp_id qty_Total

1    ?900
2    ?900
Total  ?1800

?

3.負責一點,統計每個銷售人員以及商品的數量

?

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

emp_id???????? product_id???????????? qty

01???????????????? 001??????????????????????? 200

01????????????????? 001?????????????????????? 700

01????????????????? 小計????????????????????? 900

02???????????????? 001????????????????????????? 400

02???????????????? 002????????????????????????? 500

02???????????????? 小計???????????????????????? 900

合計??????????????????????????????????????????? 1800

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

由于要統計合計以及小計,不能簡單的用nvl來產生"合計"了,要用grouping函數,來判斷者某行是否有rollup產生的合計行,

select

case when grouping(emp_id)=1 and grouping(product_id)=1 then '合計' else emp_id end emp_id,

case when grouping(emp_id)=0 and grouping(product_id)=1 then '小計' else procudt_id end product_id,

sum(qty) qty

from t_test

group by rollup(emp_id,product_id)

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

?

?

轉載于:https://www.cnblogs.com/Steven7Gao/archive/2009/11/22/1608227.html

總結

以上是生活随笔為你收集整理的SQL:给查询添加一个合计行的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。