首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

一个表,取得不同分类的各N条数据,该如何处理

2012-01-03 
一个表,取得不同分类的各N条数据如:现在有一张表:titlecategory两个字段.现在有数据:titlecategory1111622

一个表,取得不同分类的各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

热点排行