sql server 分组求最大值所在行

来源:百度知道 编辑:UC知道 时间:2024/06/11 16:49:39
有下面的表:
作者 图书ID 图书名称 出版日期
a 1 xxxxx 2008-1
a 2 xxxxx 2009-1
b 5 xxxxx 2007-1
b 8 xxxxx 2008-2
a 10 xxxxx 2009-5
b 20 xxxxx 2009-8

想得到如下的结果:
作者名称 图书ID 最近出版图书名称 出版日期
a 10 xxxxxx 2009-5
b 20 xxxxxx 2009-8

SQL语句该如何写呢?
这只是截取一些数据,实际上数据很多,作者有许多,不是只有2个,所以top 2 不可行。

----做人要以诚信为本,二楼的根本就没测试过,哪里有这样写group by 的呢。。。

---楼主想要的是这个。
create table #t(作者 nvarchar(10) ,图书ID int,图书名称 nvarchar(10), 出版日期 nvarchar(10))
insert #t
select 'a',1,'xxxxx','2008-1' union all
select 'a',2,'xxxxx','2009-1' union all
select 'b',5,'xxxxx','2007-1' union all
select 'b',8,'xxxxx','2008-2' union all
select 'a',10,'xxxxx','2009-5' union all
select 'b',20,'xxxxx','2009-8'
go

---关键查询
select * from #t,(
select 作者,max(出版日期) as '出版日期'
from #t
group by 作者) s
where #t.作者=s.作者 and #t.出版日期=s.出版日期

--删除临时数据
drop table #t

--以上在sql 2005测试通过

select 作者名称,图书ID,最近出版图书名称,max(出版日期) as 出版日期 from table group by 作者名称,最近出版图书名称,出版日期

以上,希望对你有所帮助

ytbelwxg 写的不错

如果你希望每个作者的最新著作的话 要按作者分组( group by