排序查询求助
现有这样一列,值有-1和正数值。(负数只会出现-1一种情况)
现在要根据这一列进行排序,按升序排列时希望把-1排在最后。
不知道应该如何处理。
不建议的做法是用case when将-1转为无穷大值再排序
请指教,谢谢
------解决方案-------------------- 试试这个:
--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
*/
------解决方案-------------------- 上面的代码求表中最大的product_price ,然后加1,所以这个-1 就是最大的了,再order by就可以
------解决方案-------------------- select row_number() over
(order by case when Product_Price<0 then 2 else 1 end,Product_Price)m,* from 表
试试这个肯定可以的
------解决方案--------------------
--再简化下,
select * from 表 order by case when Product_Price<0 then 2 else 1 end,Product_Price
------解决方案-------------------- 数值型直接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
*/
不过和排序规则也会有点关系
------解决方案--------------------
SELECT *
FROM 表
ORDER BY Sign(Product_Price + 1) DESC,
Product_Price ASC
------解决方案-------------------- 引用: 试试这个:
--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
*/
这个不错!
------解决方案-------------------- 引用: 数值型直接order by也可以的啊
CREATE TABLE testord