34,576
社区成员
发帖
与我相关
我的任务
分享
select AutoID ,ItemID
from TempTb t
where AutoID in (select top 3 AutoID from TempTb where t.ItemID=ItemID order by AutoID desc)
order by ItemID asc,AutoID desc
AutoID ItemID
----------- --------------------
9 01
4 01
3 01
7 02
6 02
2 02
5 03
8 04
(所影响的行数为 8 行)
if exists(select Name from sysobjects where name='TempTB' and type='U')
Drop Table TempTB
go
create Table TempTB(
AutoId int identity(1,1) not null,ItemId varchar(20),Remark varchar(100))
go
insert into TempTB(ItemId)
select '01' union all select '02' union all select '01' union all
select '01' union all select '03' union all select '02' union all
select '02' union all select '04' union all select '01'
select AutoId,ItemId
from TempTB t
where
AutoId in(select top 3 AutoId from TempTB where ItemId=t.ItemId order by AutoId desc)
order by
ItemId,
AutoId desc
/**
AutoId ItemId
----------- --------------------
9 01
4 01
3 01
7 02
6 02
2 02
5 03
8 04
(所影响的行数为 8 行)
**/
select *
from TempTB t
where
AutoId in(select top 3 AutoId from TempTB where ItemId=t.ItemId order by AutoId desc)
order by
ItemId,
AutoId desc