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

请问怎么得到新闻分类表中的每类前2条数据!
我有一个新闻表.如下:
id(自动编号)       classid(分类id)
1                                       1
2                                       1
3                                       2
4                                       3
5                                       2
6                                       2
7                                       3
8                                       4
9                                       1
....
我现要想用一条sql语句查得如下结果:
id(自动编号)       classid(分类id)
1                                       1
2                                       1
3                                       2
5                                       2
4                                       3
7                                       3
8                                       4
------------------------------------
classid的编号数是不确定的.请问偶这个sql要怎么做?
我要做的效果就是一次查新闻分类中每个分类的前两条数据.
先谢!


------解决方案--------------------
--原始数据:@news
declare @news table(id int,classid int)
insert @news
select 1,1 union all
select 2,1 union all
select 3,2 union all
select 4,3 union all
select 5,2 union all
select 6,2 union all
select 7,3 union all
select 8,4 union all
select 9,1

select * from @news a where id in (select top 2 id from @news where classid=a.classid) order by classid,id

/*
1 1
2 1
3 2
5 2
4 3
7 3
8 4
*/

------解决方案--------------------
正解
------解决方案--------------------
---方法1
Select * From 新闻表 As A Where id In
(Select Top 2 id From 新闻表 Where Classid=A.Classid Order By id)
Order By Classid,id

---方法2
Select * From 新闻表 As A Where
(Select Count(1) From 新闻表 Where Classid=A.Classid And id <=A.id Group By Classid) <3