日期:2014-05-18  浏览次数:20378 次

在线等马上结分
表     A
字段如下
id,
title,           --标题
classid,       --分类ID
date                 --时间

我想获得每个分类的最新的5条记录怎么写?
就是说如果有5个分类就获得25条记录



------解决方案--------------------
Select * from 表A as t
where id in (Select top 5 id from 表A
Where classid=t.classid order by [date] desc)
------解决方案--------------------
select * from A t where id in(select top 5 id from A where classid=t.classid order by id desc)
select * from A t where id in(select top 5 id from A where classid=t.classid order by date desc)
------解决方案--------------------
try:

CREATE TABLE T([id] int IDENTITY(1,1),title nvarchar(20),classid int,[date] datetime)

INSERT INTO T
SELECT 'Title1 ',1, '2007-04-26 ' UNION ALL
SELECT 'Title2 ',3, '2007-01-12 ' UNION ALL
SELECT 'Title3 ',3, '2007-02-22 ' UNION ALL
SELECT 'Title4 ',3, '2007-06-11 ' UNION ALL
SELECT 'Title5 ',3, '2007-03-09 ' UNION ALL
SELECT 'Title6 ',2, '2007-02-08 ' UNION ALL
SELECT 'Title7 ',2, '2007-01-06 ' UNION ALL
SELECT 'Title8 ',2, '2007-06-04 ' UNION ALL
SELECT 'Title9 ',1, '2007-02-11 ' UNION ALL
SELECT 'Title10 ',2, '2007-05-02 ' UNION ALL
SELECT 'Title11 ',1, '2007-04-01 '

SELECT title,classid,[date]

FROM T
ORDER BY classid,[date] DESC

SELECT * FROM T AS A WHERE
[ID]IN(SELECT TOP 2 [id] FROM T AS B WHERE B.classid=A.classid
ORDER BY B.classid,B.[date] DESC)
ORDER BY classid,[date] DESC
DROP TABLE T