一、相关概念
如果在对数据进行统计分析时,既需要保存查询结果,又能在查询结果下面将统计结果显示出来,我们可以使用compute by 子句。
Compute子句用于生成合计,并将其作为附加的汇总列出现在结果集的最后,当与by一起使用时,Compute子句在结果集内生成控件中断和分类汇总。可在同一查询内指定Compute by和Compute。
其语法格式如下:
[Compute
{
{Avg | count | max | min | stdev | stdevp| var | varp | sum (expression)}[,…n]
[by expressin [,….]]
}]
Compute子句中使用的聚合函数

注意:聚合函数不能使用字段别名。
二、实例说明
1、准备工作
01 |
if object_id('student','table') is not null |
06 |
ID int identity(1,1) not null, |
07 |
sex varchar(4) not null, |
10 |
constraint zhujian primary key(ID), |
11 |
constraint scorecheck check(score>0 and score<=10) |
14 |
insert into student values('男',1,2) |
15 |
insert into student values('女',2,4) |
16 |
insert into student values('女',2,6) |
17 |
insert into student values('女',1,2) |
18 |
insert into student values('男',3,3) |
19 |
insert into student values('男',2,5) |
2、group by子句
2 |
select sex,sclass,score,sum(score) as 总分 |
4 |
group by sex,sclass,score |
结果如下:
3、使用compute by子句
2 |
select sex,sclass,score,sum(score) as 总分 |
4 |
group by sex,sclass,score |
6 |
compute sum(score),avg(score),max(score),min(score) by sex |
结果如下:
完工,拜拜。
原文 : http://www.cnblogs.com/yuananyun/archive/2010/11/25.html