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

如何将几个分类的头几条记录用一句SQL查询出来?
比如这种表
type   value

1           3
1           4
1           5
1           6
2           1
2           3
2           5
2           6

比如希望每类查出两条记录

record
type   value
1         3
1         4
2         1
2         3

这种结果,SQL语句要怎么写呢

只用一句,不用select   top   2   *   from   table   where   type   =   1这类方法(也就是不人工对type这类查询条件赋值)

------解决方案--------------------
--方法一:
Select * From 表 A
Where (Select Count(*) From 表 Where type = A.type And value > A.value) < 2
Order By type, value

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

--方法三:
Select * From 表 A
Where value In (Select TOP 2 value From 表 Where type = A.type Order By value Desc)
Order By type, value
------解决方案--------------------
declare @t table(type int, value int)
insert @t
select 1, 3 union all
select 1, 4 union all
select 1, 5 union all
select 1, 6 union all
select 2, 1 union all
select 2, 3 union all
select 2, 5 union all
select 2, 6

select * from @t as a where (select count(*) from @t where type = a.type and value < a.value) < 2

/*结果
type value
----------------------------
1 3
1 4
2 1
2 3
*/
------解决方案--------------------
--方法一:
Select * From 表 A
Where (Select Count(*) From 表 Where type = A.type And value <= A.value) <= 2
Order By type, value

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

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


呵呵