2015-04-01 117 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是默认的排序(并不需要显式地指定)