一个复杂的排序很难实现

红皮猴 2006-09-06 02:49:33
ID(自增)a b(只有1和0组成)

1 3 1
2 4 0
3 5 0
4 1 1
5 2 0
6 4 1
7 6 1
8 2 0
9 3 1

要求b desc排序后,如果b为1的话就 a desc,如果b=0 就 id desc
要求上面的排序结果如下:
ID a b
7 6 1
6 4 1
9 3 1
1 3 1
4 1 1
8 2 0
5 2 0
3 5 0
2 4 0



...全文
127 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
红皮猴 2006-09-06
  • 打赏
  • 举报
回复
谢谢这个对了
九斤半 2006-09-06
  • 打赏
  • 举报
回复
create table test(ID int identity(1,1),a int,b int)
insert test(a,b)
select 3 ,1 union all
select 4 ,0 union all
select 5 ,0 union all
select 1 ,1 union all
select 2 ,0 union all
select 4 ,1 union all
select 6 ,1 union all
select 2 ,0 union all
select 3 ,1
--select * from test

select * from test
order by
case when b=1 then 0 else 1 end,
case when b=1 then a else id end desc,
id desc -- id为9与1的排序

drop table test
红皮猴 2006-09-06
  • 打赏
  • 举报
回复
上面的我运行了经过是错的
九斤半 2006-09-06
  • 打赏
  • 举报
回复
select * from tablename
order by case when b=1 then 0 else 1 end,a desc,id desc

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧