COMPUTE子句和Group By

时间:2023-01-17 15:41:12
 
 
 
 
 
 
 
 
 
 

首先声明一下,这个COMPUTE语法在SQLServer 2012之后,就废弃使用了,详情请看https://msdn.microsoft.com/library/ms144262(v=sql.110)

COMPUTE子句和Group By

下面的操作都是在SQLServer 2008版本中操作的。

1. group by
        用group by 的select字句中,只能选择集合函数和出现在group by字句中的分组列。
但对组用 having 进行筛选时,having字句使用的集合函数表达式包含的列可以不包含在select字句的选择列中。

COMPUTE子句和Group By

select bookID,sum(quentity) as 销售册数
from book
group by bookid

COMPUTE子句和Group By

用 having 筛选:

select bookID,sum(quentity) as 销售册数
from book
group by bookid
having count(orderid)>=3

COMPUTE子句和Group By

2. compute 字句

  可以这样说,compute 比 group by 更高级,group by 可以查看某一类的函数计算;而compute不光能实现这个效果,还可以显示出每一类的每一条数据。

select *
from book
compute sum(quentity)

COMPUTE子句和Group By

注意:在compute后使用 by 时,必须要在compute前使用order by 进行排序;order by 后面的字段和compute 后面的 by 所使用的字段应该是一样的。  否则如下所示:

select *
from book
compute sum(quentity) by bookid

COMPUTE子句和Group By

3. compute  by字句

select *
from book
order by bookid
compute sum(quentity) by bookid

COMPUTE子句和Group By