--> 生成測試資料: #t
if object_id('tempdb.dbo.#t'
) is
notnull
drop
table
#t
create
table
#t (id
varchar
(3),gid
int,author
varchar
(29),title
varchar
(39),
date
datetime)
insert
into
#t
select
'001'
,1,'鄒建'
,'深入淺出sqlserver2005開發管理與應用例項'
,'2008-05-10'
union
allselect
'002'
,1,'胡百敬'
,'sqlserver2005效能調校'
,'2008-03-22'
union
allselect
'003'
,1,'格羅夫groff.j.r.'
,'sql完全手冊'
,'2009-07-01'
union
allselect
'004'
,1,'kalendelaney'
,'sqlserver2005技術內幕儲存引擎'
,'2008-08-01'
union
allselect
'005'
,2,'alex.kriegel.boris.m.trukhnov'
,'sql寶典'
,'2007-10-05'
union
allselect
'006'
,2,'飛思科技產品研發中心'
,'sqlserver2000高階管理與開發'
,'2007-09-10'
union
allselect
'007'
,2,'胡百敬'
,'sqlserver2005資料庫開發詳解'
,'2008-06-15'
union
allselect
'008'
,3,'陳浩奎'
,'sqlserver2000儲存過程與xml程式設計'
,'2005-09-01'
union
allselect
'009'
,3,'趙松濤'
,'sqlserver2005系統管理實錄'
,'2008-10-01'
union
allselect
'010'
,3,'黃佔濤'
,'sql技術手冊'
,'2006-01-01'
union
allselect
'010'
,4,'黃蛋蛋'
,'sql技術手冊蛋蛋'
,'2006-01-01'
--sql查詢如下: --按gid分組,查每個分組中date最新的前2條記錄
select
* from
#t
--1.欄位id唯一時:
select
* from
#t as
t where
id in
(select
top3 id
from
#t where
gid=t.gid
order
bydate
desc
)
--2.如果id不唯一時:
select
* from
#t as
t where
2>(
select
count
(*)
from
#t where
gid=t.gid
anddate
>t.
date
)
--sql server 2005 使用新方法
--3.使用row_number()進行排位分組
select
id,gid,author,title,
date
from
(
select
rid=row_number() over(partition
bygid
order
bydate
desc
),*
from
#t )
ast
where
rid<=2
select
distinct
b.*
from
#t as
a cross
select
top(2) *
from
#t where
a.gid=gid
order
bydate
desc
) as
b
SQL查詢每個分組的前N條記錄
if object id tempdb.dbo.t is not null drop table t create table t id varchar 3 gid int,author varchar 29 title varchar 39 date datetime insert into t ...
SQL查詢每個分組的前N條記錄
在寫乙個儲存過程中,遇到了乙個問題,自己寫的 sql總是執行效率太低,於是上網搜尋,學到了乙個新招,都怪自己平時不愛學習啊,不過這個語法真的很厲害。需求 取乙個表中每個 id的最新三條資料 按照更新時間倒序取 select from t as t where 3 select count from ...
orcale 查詢分組後的前n條記錄
orcale 查詢分組後的前n條記錄 使用row number over partition by col1,col2 order by col3 desc 示例如下 select from select col1,col2,col4,row number over partition by col...