sql中having 与group by详解
GROUP BY 实例
表 "Sales":
Company Amount
W3Course 6500
IBM 5500
W3Course 7300
SQL:
SELECT Company, SUM(Amount) from Sales
结果:
Company SUM(Amount)
W3Course 19300
IBM 19300
W3Course 19300
上面的代码是无效的,这是由于被返回的列没有进行部分合计。GROUP BY 子句能解决这个问题:
SELECT Company,SUM(Amount) from Sales
GROUP BY Company
结果:
Company SUM(Amount)
W3Course 13800
IBM 5500
HAVING...
把 HAVING 加入 SQL 的原因是,WHERE 无法应用于合计函数,而如果没有 HAVING,就无法测试结果条件。
HAVING 的语法:
SELECT column,SUM(column) from table
GROUP BY column
HAVING SUM(column) condition value
表 "Sales":
Company Amount
W3Course 6500
IBM 5500
W3Course 7300
SQL:
SELECT Company,SUM(Amount) from Sales
GROUP BY Company
HAVING SUM(Amount)>10000
结果:
Company SUM(Amount)
W3Course 13800
相关文档:
create PROCEDURE pagelist
@tablename nvarchar(50),
@fieldname nvarchar(50)='*',
@pagesize int output,--每页显示记录条数
@currentpage int output,--第几页
@orderid nvarchar(50),--主键排序
@sort int,--排序方式,1表示升序,0表示降序排列
......
先来一段代码:
WITH OrderedOrders AS
(SELECT *,
ROW_NUMBER() OVER (order by [id])as RowNumber --id是用来排序的列
from table_info ) --table_info是表名
SELECT *
from OrderedOrders
WHERE RowNumber between 50 and 60;
在windows server 2003, sql server 2005 CTP,P4 2.66GHZ,1GB 内存下测试,执行时 ......
declare @ID varchar(10)
set @ID=9 --根节点
declare @i int --级数
declare @t table(ID varchar(10),ParentID varchar(10),Level int)
set @i = 1
insert into @t select @ID,0,0 --当前级,本级,如果不要的话可以注释掉或再加个参数来选择操作
insert into @t select ID,ParentID,@i from t_ ......
游标的类型:
1、静态游标(不检测数据行的变化)
2、动态游标(反映所有数据行的改变)
3、仅向前游标(不支持滚动)
4、键集游标(能反映修改,但不能准确反映插入、删除)
游标使用顺序:
1、定义游标
2、打开游标
3、使用游标
  ......