mysql 增加合计行_如何给SQL查询添加合计行

本文介绍了如何在SQL查询中添加合计行,提供了一个在MS SQL Server 2005中实现的例子,以及如何统计每个销售人员及商品的总数量。通过使用`GROUP BY ROLLUP`,可以生成包含合计和小计的复杂查询结果。

SQL查询是SQL数据库的核心功能,下面为您介绍给SQL查询添加合计行的方法示例,供您参考,希望对您学习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

SQL查询的结果如下所示

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为数据库本身有的行。

【编辑推荐】

【责任编辑:段燃 TEL:(010)68476606】

点赞 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值