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
因作者水平有限,難免有疏漏錯誤之處,懇請讀者不吝批評指正