日期:2014-05-19  浏览次数:20509 次

一个表,取得不同分类的各N条数据
如:现在有一张表:

title
category
两个字段.

现在有数据:
title         category
1111           6
2222           7
3333           6
4444           6

现在想用一个sql取得,当N等于2时.
得到数据:1111     2222       333


------解决方案--------------------
--如果category相同的時候,title不會重復

--方法一:
Select * From 表 A
Where (Select Count(*) From 表 Where category = A.category And title < A.title) < 2
Order By category, title

--方法二:
Select * From 表 A
Where Exists (Select Count(*) From 表 Where category = A.category And title < A.title Having Count(*) < 2)
Order By category, title

--方法三:
Select * From 表 A
Where title In (Select TOP 2 title From 表 Where category = A.category Order By title)
Order By category, title