求SQL(80分)

  • 主题发起人 主题发起人 labixiaoxin
  • 开始时间 开始时间
L

labixiaoxin

Unregistered / Unconfirmed
GUEST, unregistred user!
在表1中有字段ftype,所有记录中这个字段值有0--7几种可能,现想用一个SELECT语句选出ftype值为<3的所有记录(其中又按其它一些字段进行排序,但请注意排序条件不包括ftype字段),然后后面再跟上ftype值为>=3而<5的所有记录(其中又按其它一些字段进行排序,但请注意排序条件不包括ftype字段),然后后面再跟上ftype值为>=5而<=7的所有记录(其中又按其它一些字段进行排序,但请注意排序条件不包括ftype字段)。我原来用UNION联合上述三个数据集,但SQL又不能在每个数据集进行order by,请问我的想法如何实现。谢谢。
附我原来想用但错误的SQL:
select * from table1 where ftype<3 order by field1,field2
union
select * from table1 where ftype>=3 and ftype<5 order by field1,field2
union
select * from table1 where ftype>=5 and ftype<=7 order by field1,field2
 
select *
from
(select top 100 percent *
from table1 where ftype<3 order by field1,field2) a
union
select *
from
(select top 100 percent *
from table1 where ftype>=3 and ftype<5 order by field1,field2) b
union
select *
from
(select top 100 percent *
from table1 where ftype>=5 and ftype<=7 order by field1,field2) c

没测试过!?
 
select a.* from (
select 1 as id,table1.* from table1 where ftype<3
union all
select 2 as id table1.* from table1 where ftype>=3 and ftype<5
union all
select 3 as id,table1.* from table1 where ftype>=5 and ftype<=7 ) a
order by a.id,a.field1,a.field2
 
union 只能最后有一个order by,

select 1 as id,* from table1 where ftype<3
union all
select 2 as id,* from table1 where ftype>=3 and ftype<5
union all
select 3 as id,* from table1 where ftype>=5 and ftype<=7
order by id,field1,field2

就行了
 
yhhe正解,看上去其实三种排列都是相同顺序的,结果可能有点不同,但可以有
 
多人接受答案了。
 
后退
顶部