34,594
社区成员
发帖
与我相关
我的任务
分享
if not object_id('tb') is null
drop table tb
Go
Create table tb([id] int,[关联ID] int,[内容] nvarchar(6))
Insert tb
select 1,1,N'0000d' union all
select 2,1,N'11111g' union all
select 3,1,N'22222e' union all
select 4,2,N'0000w' union all
select 5,2,N'111112' union all
select 6,2,N'222223' union all
select 7,3,N'0000w' union all
select 8,4,N'11111e' union all
select 9,4,N'22222w' union all
select 10,5,N'22222d'
Go
select *
from tb a
where not exists(select 1
from tb
where 关联ID=a.关联ID and [id]>a.[id])
/*
id 关联ID 内容
----------- ----------- ------
3 1 22222e
6 2 222223
7 3 0000w
9 4 22222w
10 5 22222d
(5 行受影响)
*/
--> --> (wufeng4552)生成測試數據
if not object_id('tb') is null
drop table tb
Go
Create table tb([id] int,[关联ID] int,[内容] nvarchar(6))
Insert tb
select 1,1,N'0000d' union all
select 2,1,N'11111g' union all
select 3,1,N'22222e' union all
select 4,2,N'0000w' union all
select 5,2,N'111112' union all
select 6,2,N'222223' union all
select 7,3,N'0000w' union all
select 8,4,N'11111e' union all
select 9,4,N'22222w' union all
select 10,5,N'22222d'
Go
select *
from tb t
where ID=(select max(ID)
from tb
where 关联ID=t.关联ID)
order by 关联ID
/*
id 关联ID 内容
----------- ----------- ------
3 1 22222e
6 2 222223
7 3 0000w
9 4 22222w
10 5 22222d
(5 個資料列受到影響)
*/
select *
from tb t
where ID=(select max(ID)
from tb
where 关联ID=t.关联ID)