请教一个sql查询(select语句) (50分)

  • 主题发起人 主题发起人 NewLearner
  • 开始时间 开始时间
N

NewLearner

Unregistered / Unconfirmed
GUEST, unregistred user!
在member表中有数字型字段unit,取值1-3,代表3种不同的类别
我想通过一条select查出3种unit的前3条记录(每种unit内按ID号升序),
比如
id unit
------------
10 1
9 1
8 1
14 2
13 2
11 2
5 3
4 3
3 3

注意: unit的类别只是目前有3种,也可能是更多种
 
用union就可以了。
如(oracle)
select * from menber where id=1 and rownumber<=3
union
select * from menber where id=2 and rownumber<=3
union
select * from menber where id=3 and rownumber<=3
不过这样好象比较土 ^_^
 
select top 3 d1.id,d1.unit from (select id as id,unit as unit from number where unit=1 order by id) d1
union
select top 3 d2.id,d1.unit from (select id as id,unit as unit from number where unit=2 order by id) d2
union
select top 3 d3.id,d1.unit from (select id as id,unit as unit from number where unit=3 order by id) d3
 
注意: unit的类别只是目前有3种,也可能是更多种无法固定的情况
为了节省资源,最好只用一个SELECT
 
Select unit,id
From Table1 AA
Where id in (Select Top 3 id From Table1 where unit=AA.unit Order by id)
Order by unit,id
 
接受答案了.
 

Similar threads

D
回复
0
查看
834
DelphiTeacher的专栏
D
D
回复
0
查看
880
DelphiTeacher的专栏
D
D
回复
0
查看
617
DelphiTeacher的专栏
D
D
回复
0
查看
744
DelphiTeacher的专栏
D
D
回复
0
查看
718
DelphiTeacher的专栏
D
后退
顶部