Oracle--排序
1.排序有升序和降序之分:
ASC表示升序排序,DESC表示降序排序.如果不指明排序顺序,默认的排序顺序为升序ASC.
2.对排序字段中包含null值的处理:
nulls first: null值排在最前面;
select name, chinese from zj_test order by chinese nulls first;
nulls last: null值排在最后面;
select name, chinese from zj_test order by chinese nulls last;
注意:是nulls first和nulls last,不是null
3.以表中某些字段的加减乘除作为排序标准:
select name, (chinese + math) as score from zj_test order by score;
4.decode()函数的使用
-- 通过decode()函数,sex值为男的记录被转换为了2,而其他的记录都是1 select name, sex from zj_test order by decode (sex, '男', 2, 1);
5.在order by中使用case语句
case语句分为两种Case Simple Expression和Case Search Expression:
Case Simple Expression:
1 CASE Column1 2 WHEN V1 THEN R1 3 WHEN V2 THEN R2 4 ELSE R3 5 END
Case Search Expression:
1 CASE 2 WHEN C1=V1 THEN R1 3 WHEN C2=V2 THEN R2 4 ELSE R3 5 END
范例:
-- between...and...前后都是闭区间
1 select 2 grade, sex, name, chinese 3 from 4 zj_test 5 order by 6 case grade 7 when '一年级' then 1 8 when '二年级' then 2 9 when '三年级' then 3 end, 10 case 11 when sex = '女' then 1 12 else 2 end, 13 case 14 when chinese >= 90 then 1 15 when chinese between 80 and 89 then 2 16 else 3 end;
6.order by 数字
-- 本例中表示,将按照select后面查询内容的第2列排序,即chinese,如果数字为0或超出查询出的列数就会报错。 select name, chinese from zj_test order by 2;
但是,如何chinese字段为varchar2类型,需要使用to_number(将varchar2类型转为数字)时,这种写法将无效;
select name, chinese from zj_test order by to_number(2);
(排序错误)
select name, chinese from zj_test order by to_number(chinese);
(排序正确)