order by colname desc 倒序
order by colname ase 正序
order by colname ase nulls fisrst 正序,但是为空的放到最前面
order by 3 desc 以第三列排序,比较像 count(3) 中的3 ,是指第三列
ps: 注意有些时候要注意进行数据类型的转换
eg:
创建表(也可以用dual配合with来创建临时表)
1 -- Create table 2 create table DEMO 3 ( 4 n_iden NUMBER, 5 c_order_code NVARCHAR2(50), 6 c_order_name NVARCHAR2(50), 7 c_friut NVARCHAR2(50), 8 c_amount NUMBER(20,4), 9 d_build DATE, 10 c_buyer NVARCHAR2(50), 11 c_seller NVARCHAR2(50) 12 ) 13 tablespace MYORCL1 14 pctfree 10 15 initrans 1 16 maxtrans 255 17 storage 18 ( 19 initial 64K 20 next 1M 21 minextents 1 22 maxextents unlimited 23 ); 24 -- Add comments to the columns 25 comment on column DEMO.n_iden 26 is 'ID'; 27 comment on column DEMO.c_order_code 28 is '订单号'; 29 comment on column DEMO.c_order_name 30 is '订单名称'; 31 comment on column DEMO.c_friut 32 is '水果类型'; 33 comment on column DEMO.c_amount 34 is '水果数量'; 35 comment on column DEMO.d_build 36 is '创建日期'; 37 comment on column DEMO.c_buyer 38 is '订货人'; 39 comment on column DEMO.c_seller 40 is '买货人';
插入数据:
insert into DEMO (N_IDEN, C_ORDER_CODE, C_ORDER_NAME, C_FRIUT, C_AMOUNT, D_BUILD, C_BUYER, C_SELLER) values (1, 'order_num1', '第一单', '苹果', 1.0000, to_date('11-01-2017', 'dd-mm-yyyy'), '1', null); insert into DEMO (N_IDEN, C_ORDER_CODE, C_ORDER_NAME, C_FRIUT, C_AMOUNT, D_BUILD, C_BUYER, C_SELLER) values (3, 'order_num1', '第一单', '香蕉', 3.0000, to_date('11-01-2017', 'dd-mm-yyyy'), '11', null); insert into DEMO (N_IDEN, C_ORDER_CODE, C_ORDER_NAME, C_FRIUT, C_AMOUNT, D_BUILD, C_BUYER, C_SELLER) values (4, 'order_num2', '第二单', '苹果', 4.0000, to_date('10-01-2017', 'dd-mm-yyyy'), '12', null); insert into DEMO (N_IDEN, C_ORDER_CODE, C_ORDER_NAME, C_FRIUT, C_AMOUNT, D_BUILD, C_BUYER, C_SELLER) values (5, 'order_num2', '第二单', '橘子', 5.0000, to_date('10-01-2017', 'dd-mm-yyyy'), '13', null); insert into DEMO (N_IDEN, C_ORDER_CODE, C_ORDER_NAME, C_FRIUT, C_AMOUNT, D_BUILD, C_BUYER, C_SELLER) values (2, 'order_num1', '第一单', '橘子', 2.0000, to_date('11-01-2017', 'dd-mm-yyyy'), '2', null); commit;
简单的进行排序:
select * from DEMO order by c_buyer
结果如下:
可以看出并不是按照c_buyer的从小到大进行排序的.这时候就要进行字符格式转换
select * from DEMO order by to_number(c_buyer)
结果如下
因为这一步不返回表(而是返回游标),使用了ORDER BY子句的查询不能用作表表达式。表表达式包括:视图、内联表值函数、子查询、派生表和共用表达式。它的结果必须返回给期望得到物理记录的客户端应用程序。例如,下面的派生表查询无效,并产生一个错误:
select *
from(select orderid,customerid from orders order by orderid)
as d
下面的视图也会产生错误
create view my_view
as
select *
from orders
order by orderid
在SQL中,表表达式中不允许使用带有ORDER BY子句的查询,而在T—SQL中却有一个例外(应用TOP选项)。
所以要记住,不要为表中的行假设任何特定的顺序。换句话说,除非你确定要有序行,否则不要指定ORDER BY 子句。排序是需要成本的,SQL Server需要执行有序索引扫描或使用排序运行符。
ps:
除了上面的几个关键字,还有 rownum
执行顺序,如下:
取code为 C3 的数据
错误代码如下:
select * from t_class where rownum <2 order by code desc
正确代码如下:
select * from (
select * from t_class order by code desc
) where rownum <2
因作者水平有限,难免有疏漏错误之处,恳请读者不吝批评指正