SQLSERVER——Compute字句

来源:互联网 发布:阿里云vps能翻墙吗 编辑:程序博客网 时间:2024/05/12 15:30

使用Compute by子句和行统计函数(count,sum,max,avg,min等),可以统计排序中结果完全相同的列,统计值作为查询结果以附加行的形式显示

语法:Compute avg|count|max|min|sum by 表达式

 

--模拟一张商品表
--id:编号
--name:商品名称
--type:类型
--amount:数量
create table temp
(
    id int identity(1,1) primary key,
    [name] varchar(50),
    [type] int ,
    amount int
)
go
--插入测试数据
insert into temp([name],[type],amount)
select 'aa',1,10 union all
select 'bb',1,15 union all
select 'cc',1,10 union all
select 'dd',2,10 union all
select 'ee',2,30 union all
select 'ff',2,10 union all
select 'gg',3,10 union all
select 'hh',3,10 union all
select 'jj',4,50 union all
select 'kk',4,10 union all
select 'll',4,40 union all
select 'mm',4,10

 

现在要查询数据,并根据每个类别进行数据汇总,最后进行总数量的汇总:

select id,[name],[type],amount from temp order by [type]
compute sum(amount) by [type]
compute sum(amount)

 

出现的结果如下:

id  name type amount
1   aa   1    10
2   bb   1    15
3   cc   1    10
sum
35

id  name type amount
4   dd   2    10
5   ee   2    30
6   ff   2    10
sum
50

id  name type amount
7   gg   3    10
8   hh   3    10
sum
20

id  name type amount
9   jj   4    50
10  kk   4    10
11  ll   4    50
12  mm   4    10
sum
110

sum
215

 

不难看出,结果其实是在一个查询结果中包含了三个子查询(根据type不同而分的组),每个子查询又包含两个子查询(一个是详细信息,一个是统计信息)

 

compute by 子句的规则:

(1)不能将distinct与行统计函数一起使用

(2)compute ??? by 子句中 ???出的列必须出现在选择列表中

(3)不能在含有compute by 子句的语句中使用select into 子句,因为包括compute 子句的语句会产生不规则的行。

(4)如果使用了compute by子句,则必须使用order by 子句, 而且compute by子句中的列必须包含在orderby 子句中,并且对列的前后顺序和起始项都要一致(说白了compute by子句中的列必须是orderby子句中列表的全部,或者前边的连续几个)。

(5)如果compute 省略了 by ,则order by 也可以省略

(6)如果compute by 子句包含多列时,会将一个组(第一个列分的组)分成若干个子组(利用后面的列),并对每层子组进行统计。

(7)使用多个compute by子句时,会分别按不同的组统计出结果。详细信息还是按照正常的第一个分组方式显示。

(8)compute by 子句中可以使用多个统计函数,他们互不影响

(9)compute by 子句中可以不包含by ,而只用compute  此时不对前面信息分组,而只对全部信息进行统计。