表:tab
ID Name ShuLiang
1 a 5
2 b 1
3 a -1
4 c 5
查询结果要分为两类,数量为正数的排在上面,每一类还要按照ID顺序排列,比如:
ID Name ShuLiang
1 a 5
2 b 1
4 c 5
3 a -1
------解决方案--------------------
select * from tab order by case when ShuLiang>0 then 0 else 1 end,ID
------解决方案--------------------
通过在orader by中加上case when来排序,是这样吗:
drop table tab
go
create table tab(ID int,Name varchar(10), ShuLiang int)
insert into tab
select 1 ,'a', 5
union all select 2 ,'b', 1
union all select 3 ,'a', -1
union all select 4 ,'c', 5
select *
from tab
order by case when ShuLiang > 0
then 0
else 1
end,
id
/*
ID Name ShuLiang
1 a 5
2 b 1
4 c 5
3 a -1
*/
------解决方案--------------------
用case when 来判断就够了。别人写了我就不写了

------解决方案--------------------
"数量为正的放在上面” ---------大于0为一类,小于0为一类,为了直观假设大于0为1,小于0为-1,大的放前面,降序排列
“每一类再按ID排序” ---------ID为排序次关键字,放在后面
代码如下:
CREATE TABLE tab(ID int,name varchar(10),ShuLiang int)
GO
INSERT INTO tab
SELECT 1,'a',5 UNION ALL
SELECT 2,'b',1 UNION all
SELECT 3,'a',-1 UNION all
SELECT 4,'c',5
GO
SELECT * FROM tab
ORDER BY (CASE WHEN ShuLiang > 0 THEN 1 ELSE -1 END) DESC,ID