sql server 裏的 over

create table OverTableTest
(
 id int identity(1,1),--ID
 Val int, --值
 typ int, --類型
)
go
declare @cou int
set @cou=1
while @cou<50
begin
 insert into OverTableTest
  select @cou,@cou%5+1
 
 set @cou=@cou+1
end
go

select * from OverTableTest
/*
 通常我們會用到的是情景是:分頁(row_Number)
 示例:
*/
;with mycte as
(
 select row=ROW_NUMBER() over (order by id desc) ,* from
 OverTableTest
)select * from mycte where row BETWEEN 10 and 20
/*
 在上面的情況下我經常用到,
 但是卻一直沒有追問 Over到底是做什麼用的啊
*/
/*
 應用環境2 分組獲取前幾名
 就好像,考試了,要獲取每科排名前3的同學
 SQL:
*/
;with mycte as
(
 select row=ROW_NUMBER() over (partition by typ order by val desc) ,* from
 OverTableTest
)select * from mycte where row<=3
/*
 在這個示例中 加上了partition by 就是進行分組統計了
 我們再來進行第三個示例:
 按照類別獲取 類別數量,同時按照類別數量最多的排序
*/
select Cunt=count(0) over(partition by typ) ,* from
 OverTableTest  order by Cunt desc,typ,id
-----------------------------------------------------------------
/*
 今天例子就說到這裏了,運行結果 大家複製直接執行就好了
*/

 

轉的別人的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章