排序查询求助

人间太皮 2014-02-17 12:03:39


现有这样一列,值有-1和正数值。(负数只会出现-1一种情况)

现在要根据这一列进行排序,按升序排列时希望把-1排在最后。

不知道应该如何处理。

不建议的做法是用case when将-1转为无穷大值再排序

请指教,谢谢
...全文
130 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
發糞塗牆 2014-02-17
  • 打赏
  • 举报
回复
数值型直接order by也可以的啊
CREATE TABLE testorder
(a FLOAT)
INSERT INTO testorder
SELECT 1.0
UNION ALL 
SELECT -1
UNION ALL 
SELECT 0

SELECT * FROM testorder ORDER BY a desc

/*
a
----------------------
1
0
-1
*/
不过和排序规则也会有点关系
t101lian 2014-02-17
  • 打赏
  • 举报
回复

--再简化下,
  select * from 表 order by case when Product_Price<0 then 2 else 1 end,Product_Price
t101lian 2014-02-17
  • 打赏
  • 举报
回复
select row_number() over
 (order by case when Product_Price<0 then 2 else 1 end,Product_Price)m,* from 表
试试这个肯定可以的
LongRui888 2014-02-17
  • 打赏
  • 举报
回复
上面的代码求表中最大的product_price ,然后加1,所以这个-1 就是最大的了,再order by就可以
LongRui888 2014-02-17
  • 打赏
  • 举报
回复
试试这个:
--drop table t

create table t(product_price numeric(10,1))

insert into t
select -1.0 as product_price union all
select 0.0  union all
select 1.0  union all
select 2.0 
go


select t.*
from t
inner join
(
select max(product_price) max_price from t
)tt
 on 1=1
order by case when t.product_price = -1 then tt.max_price+1 else t.product_price end
/*
product_price
0.0
1.0
2.0
-1.0
*/
KeepSayingNo 2014-02-17
  • 打赏
  • 举报
回复
楼主试试这个

select * from testorder where a<>-1
union all
select * from testorder where a=-1
KeepSayingNo 2014-02-17
  • 打赏
  • 举报
回复
引用 5 楼 DBA_Huangzj 的回复:
数值型直接order by也可以的啊
CREATE TABLE testorder
(a FLOAT)
INSERT INTO testorder
SELECT 1.0
UNION ALL 
SELECT -1
UNION ALL 
SELECT 0

SELECT * FROM testorder ORDER BY a desc

/*
a
----------------------
1
0
-1
*/
不过和排序规则也会有点关系
楼主的需求是“按升序排列时希望把-1排在最后”,也就是结果是 0 1 -1
直面人生 2014-02-17
  • 打赏
  • 举报
回复
引用 1 楼 yupeigu 的回复:
试试这个:
--drop table t

create table t(product_price numeric(10,1))

insert into t
select -1.0 as product_price union all
select 0.0  union all
select 1.0  union all
select 2.0 
go


select t.*
from t
inner join
(
select max(product_price) max_price from t
)tt
 on 1=1
order by case when t.product_price = -1 then tt.max_price+1 else t.product_price end
/*
product_price
0.0
1.0
2.0
-1.0
*/
这个不错!
jorkin_me 2014-02-17
  • 打赏
  • 举报
回复

SELECT *
FROM   表
ORDER  BY Sign(Product_Price + 1) DESC,
          Product_Price ASC 

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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