查询子表中最新记录,不是 Select TOP 1

prodever2006 2010-06-12 02:22:52
子表c的字段
Owner,Name,DateAdd

其中,c.Owner与主表f.Id关联

要求查询c中
若干c.Owner值相同记录中最新的一条记录。

谢谢!
...全文
58 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
永生天地 2010-06-12
  • 打赏
  • 举报
回复

if object_id('f') is not null drop table f
go
create table f (
Id int ,Name varchar(10))
insert f
select 1 ,'张三' union all
select 2 ,'李四'

if object_id('c') is not null drop table c
go
create table c (
Owner int,Name varchar(10),DateAdd int)
insert c
select 1 ,'语文', 2009 union all
select 2 ,'数学', 2009 union all
select 1 ,'英语', 2010
go

select * from c a,f b
where a.Owner=b.Id
and (select count(1) from c where Owner=a.Owner and DateAdd>a.DateAdd)=0
/*
Owner Name DateAdd Id Name
----------- ---------- ----------- ----------- ----------
1 英语 2010 1 张三
2 数学 2009 2 李四

(所影响的行数为 2 行)
*/
prodever2006 2010-06-12
  • 打赏
  • 举报
回复
sql server 2000
prodever2006 2010-06-12
  • 打赏
  • 举报
回复
主表f
Id,Name
1 张三
2 李四

子表c的字段
Owner,Name,DateAdd
1 语文 2009
2 数学 2009
1 英语 2010

其中,c.Owner与主表f.Id关联

要求查询出子表中 各Owner值 对应的最新的记录
比如得到下面的结果
1 英语 2010 (对应owner=1)
2 数学 2009 (对应owner=2)


谢谢!
永生天地 2010-06-12
  • 打赏
  • 举报
回复
select * from(
select *,rn=row_number()over(partition by c.Owner order by getdate()) from c,f where c.Owner=f.Id
) t where rn=1
jiongjiongtang 2010-06-12
  • 打赏
  • 举报
回复
ORDER BY 排序字段 DESC
caixia615 2010-06-12
  • 打赏
  • 举报
回复
要ORDER BY 你的日期字段 或者 ID DESC

34,873

社区成员

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

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