1. 程式人生 > >Sql多條件排序

Sql多條件排序

sel http dao 留言 .net get 創建 cat 暴力

多條件排序可以通過在order by語句後面使用case when then條件語句來實現。

select * from 表名 ORDER BY case when 條件 then 0 else 1 end

例子:

1.創建表case_test

共有id,case_type,case_location,case_way四個字段。

2.導入數據:

INSERT INTO "XIANGZH"."case_test" VALUES (1, 盜竊案, 臺東, 技術開鎖);
INSERT INTO "XIANGZH"."case_test" VALUES (88, 謀殺案
, 臺東, 技術開鎖); INSERT INTO "XIANGZH"."case_test" VALUES (99, 盜竊案, 江西路, 技術開鎖); INSERT INTO "XIANGZH"."case_test" VALUES (5, 盜竊案, 臺東, 暴力開鎖); INSERT INTO "XIANGZH"."case_test" VALUES (6, 盜竊案, 江西路, 暴力開鎖); INSERT INTO "XIANGZH"."case_test" VALUES (7, 謀殺案, 臺東, 暴力開鎖); INSERT
INTO "XIANGZH"."case_test" VALUES (8, 謀殺案, 江西路, 技術開鎖); INSERT INTO "XIANGZH"."case_test" VALUES (9, 謀殺案, 江西路, 暴力開鎖); INSERT INTO "XIANGZH"."case_test" VALUES (10, 盜竊案, 臺東, 技術開鎖);

未排序截圖:

技術分享

3.多條件分組排序

select * from "case_test" ORDER BY 
case when "case_type"=盜竊案 then 0 else 1
end, case when "case_location" = 臺東 then 0 else 1 end, case when "case_way" = 技術開鎖 then 0 else 1 end ASC

查詢結果是按照條件分組排序,截圖:

技術分享

4.滿足條件個數排序

select * from "case_test" ORDER BY 
case 
when "case_type"=盜竊案 and "case_location" = 臺東 and "case_way" = 技術開鎖 then 0
when "case_type"=盜竊案 and "case_location" = 臺東 then 1
when "case_type"=盜竊案 and "case_way" = 技術開鎖 then 2
when "case_location" = 臺東 and "case_way" = 技術開鎖 then 3
when "case_type"=盜竊案 then 4
when "case_location" = 臺東 then 5
when "case_way" = 技術開鎖 then 6
else 7
end

查詢結果是按照滿足條件的個數排序,截圖:

技術分享

如果有更合理的sql寫法,歡迎留言討論。

參考:

ORACLE按條件排序的例子

Oracle怎麽按條件排序

Sql多條件排序