求教

无心雨云 2010-07-05 04:29:54
表结构
id 关联ID 内容
1 1 0000d
2 1 11111g
3 1 22222e
4 2 0000w
5 2 111112
6 2 222223
7 3 0000w
8 4 11111e
9 4 22222w
10 5 22222d

想得到
3 1 22222e
6 2 222223
7 3 0000w
9 4 22222w
10 5 22222d
...全文
49 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
给我力量 2010-07-05
  • 打赏
  • 举报
回复
select * from table where id in(select max(id) from table group by 关联id )


shixixi1987 2010-07-05
  • 打赏
  • 举报
回复
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
go
select * from 表名 where id in( select max(id) id from 表名 group by 关联ID)
go
shixixi1987 2010-07-05
  • 打赏
  • 举报
回复
select * from 表名 where id in( select max(id) id from 表名 group by 关联ID)
黄_瓜 2010-07-05
  • 打赏
  • 举报
回复
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 行受影响)


*/
水族杰纶 2010-07-05
  • 打赏
  • 举报
回复
--> --> (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 個資料列受到影響)

*/
  • 打赏
  • 举报
回复

呵呵……
水族杰纶 2010-07-05
  • 打赏
  • 举报
回复
select *
from tb t
where ID=(select max(ID)
from tb
where 关联ID=t.关联ID)

34,594

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧