怎么查出员工信息表中来自不同各地的年纪最大的前几条信息
发布网友
发布时间:2024-02-29 19:03
我来回答
共1个回答
热心网友
时间:2024-03-02 21:05
你的意思是对每个地区各捞几笔年纪最大的信息,对吧,这得用游标来解决了
假设员工信息表为UserInfo,地区字段Region,年纪字段Age,则可用下面语句完成。只需把UserInfo,Region,Age替换成对应字串,在查询分析器中Run下面语句即可。
如果是对各地区捞一笔最大年龄记录,则很简单:select Region ,MAX(Age) as MaxAge from UserInfo group by Region
如果不分地区更简单了:select top 5 * from UserInfo order by Age desc
代码:
declare @Region nvarchar(50)
select top 0 * into #Result from UserInfo
declare currRegion cursor for select distinct Region from UserInfo
open currRegion
fetch next from currRegion into @Region
while @@FETCH_STATUS =0
begin
insert into #Result select top 5 * from UserInfo where Region = @Region order by Age desc
fetch next from currRegion into @Region
end
close currRegion
deallocate currRegion
select * from #Result order by Region,Age
drop table #Result
如果表不大可以用下列语句(如果表太大会影响服务器性能):
SELECT * , row_number() OVER ( Partition BY Region ORDER BY Tran_Date DESC ) AS NUM INTO #Temp FROM UserInfo SELECT * FROM #TEMP WHERE NUM < 6