2016-02-22 35 views
2

我有以下價格範圍的行,$0-$50, $50-$100, $100-$500, $500+定義爲varchar2列。我想按照上面給出的順序對值進行排序。任何人都可以建議我這樣做。排序在oracle查詢的價格範圍內

+0

你可以提供你曾嘗試過什麼嗎? –

+0

我不明白從哪裏開始以及如何去做。 – user525146

+0

請提供表格結構,樣本數據和預期結果。猜測你想用'case'語句'命令'。 – sgeddes

回答

2

你可以使用regexp_substr()做你想做的事。然而,case可能是最簡單的:

order by (case pricerange 
      when '$0-$50' then 1 
      when '$50-$100' then 2 
      when '$100-$500' then 3 
      when '$500+' then 4 
      else 999 
      end) 
+0

如果我使用這種情況,如何執行desc命令? – user525146

+0

只需在表達式:'end)desc'後添加'desc'。 –

+0

可以像這樣按順序使用'decode'和'regexp_substr()'?通過解碼命令(regexp_substr('1 asc nulls last','^(\ d)*') - 7),'-1','1 asc nulls last'(case pricerange when'$ 0- $ 50 'then 1 when'$ 50- $ 100'then 2 when'$ 100- $ 500'then 3 when'$ 500 +'then 4 else 999 end))'因爲它不適合我,所以排序失敗查詢 – user525146

0

也許你考慮到這樣的事情。 WIDTH_BUCKET(exp, min,max,buckets_cnt)。該函數將exp分配給它的存儲桶。它會創建buckets_cnt + 2 以下示例創建5個存儲桶WIDTH_BUCKET(price,50,500,3)

(500-50)/3 = 150 
0 - <50 less than min 
1 - (50 : 200) 
2 - (200 : 350) 
3 - (350 : 500) 
4 - 500> more than max 



with prod_table as(select 'A' prod_name, 49 price from dual 
        union all 
        select 'B' prod_name, 100 price from dual 
        union all 
        select 'c' prod_name, 200 price from dual 
         union all 
        select 'd' prod_name, 300 price from dual 
         union all 
        select 'e' prod_name, 1000 price from dual) 
SELECT prod_name, price,WIDTH_BUCKET(price,50,500,3) from prod_table order by WIDTH_BUCKET(price,50,500,3) desc