一、相關概念
如果在對數據進行統計分析時,既需要保存查詢結果,又能在查詢結果下面將統計結果顯示出來,我們可以使用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
02
drop
table
student
03
go
04
create
table
student
05
(
06
ID
int
identity(1,1)
not
null
,
07
sex
varchar
(4)
not
null
,
08
sclass
varchar
(10),
09
score
int
,
10
constraint
zhujian
primary
key
(ID),
11
constraint
scorecheck
check
(score>0
and
score<=10)
12
13
)
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子句
1 |
--group字句 |
2 |
select sex,sclass,score, sum (score) as 總分 |
3 |
from student |
4 |
group by sex,sclass,score |
5 |
order by sex |

1 |
--comlpute by字句 |
2 |
select sex,sclass,score, sum (score) as 總分 |
3 |
from student |
4 |
group by sex,sclass,score |
5 |
order by sex |
6 |
compute sum (score), avg (score), max (score), min (score) by sex |

原文 : http://www.cnblogs.com/yuananyun/archive/2010/11/25.html