2015-04-01 120 views
0

我想通過聲明創建一個動態順序。ORDER BY與CASE子句

其目的是讀取每日計劃覆蓋表(0到*記錄)並決定在選定日期使用全局覆蓋或存儲覆蓋。

我想過使用像下面這樣的case子句,但它沒有按預期工作。

select * from schedule sdl 
where day = 3 
and (sdl.store_id = 23331 or sdl.store_id is null) 
order by 
case when sdl.force is true 
then 'sdl.store_id nulls first' 
else 'sdl.store_id nulls last' 
end 
limit 1 

是否可以使用case語句創建一個order-by語句?或者對這個問題有更好的解決方法。

+0

我覺得有人已經回答了這個問題: http://stackoverflow.com/questions/10645131/sql-case-statement-in-order-by-條款 – IHTS 2015-04-01 20:05:05

回答

1

你似乎是在正確的軌道上。您只需爲每一行生成一個值,並使其對您希望如何排序有意義。

select * 
from schedule sdl 
where day = 3 
    and (sdl.store_id = 23331 or sdl.store_id is null) 
order by case when sdl.store_id is null and sdl.force then 0 --nulls in front 
      when sdl.store_id is null and not sdl.force then 2 --nulls in back 
      else 1 end; --everything else in the middle 

測試上的PostgreSQL 9.4.1

+0

只是爲了您的答案。如果你想爲中間結果得到不同的順序而不是其他1 - > else row_number()over(primary_key_id order by primary_key_id desc分區)結束 – mallix 2015-04-02 09:52:12

+0

這就是按照它們出現在結果集。只有「零空」的三個值爲0,「非空」爲1,「空最後」爲2,這提供了更多的分組效果,允許按照標準提供更多的順序以在每個組內提供合理的排序。 – TommCatt 2015-04-03 03:25:18

+0

更不用說,值2不能再用於「空最後」組。您將不得不跟蹤生成的行號的數量,並將其設置爲大於最後一行數量的某個值。 – TommCatt 2015-04-03 03:33:57

-2

嘗試在select子句中使用大小寫,然後按該字段進行排序。

沒有測試我應該是這個樣子的是

select *, 
case when sdl.force is true 
    then 'sdl.store_id nulls first' 
    else 'sdl.store_id nulls last' 
    end as orderfield 
from schedule sdl 
where day = 3 
and (sdl.store_id = 23331 or sdl.store_id is null) 
order by orderfield 
limit 1 
+0

你能發佈或鏈接到代碼嗎? – mallix 2015-04-01 20:23:04

+0

我不認爲這是有效的。 'sdl.store_id空頭':: text因此它被解釋爲文本而不是實際的store_id參考 – mallix 2015-04-01 21:09:17

+0

哦,是的,請參閱我先忘記了空值,最後是空值。對不起 – 2015-04-02 09:57:26

0

是有可能,在你的問題評論的鏈接顯示了一個有效的例子,但它看起來像你的問題是「第一個零位/最後的」 。這些不是有效的postgres結構。您的查詢應該是這樣

select * from schedule sdl 
where day = 3 and (sdl.store_id = 23331 or sdl.store_id is null) 
order by 
case when sdl.force is true 
    then sdl.store_id end desc, 
case when sdl.force is false 
    then sdl.store_id end   
limit 1 

ASC是默認的排序(並不需要顯式地指定)