是否可以根据WHERE条件成功进行ORDER ?



假设我有一个名为temp的表,它包含int属性ab:

create table temp (id int primary key, a int, b int);
insert into temp values(1, 1, 1);
insert into temp values(2, -1, 1);
insert into temp values(3, -1, -1);

我需要根据哪一个WHERE条件成功对一些SELECT结果进行排序。一个原始但不工作的例子:

select *, priority from temp where (
case 
when a > 0 and b > 0 then 1 
when a > 0 or b > 0 then 2 
else 0 
end
as priority
) > 0 order by priority asc

它类似于"如果ab都是正的,那么这个元组将是第一个。如果至少有一个属性是正的,那么这个元组在第一个属性之后。否则不要选择

所以有可能保存CASE结果在ORDER中使用它吗?或者可能有解决方案,而不必在WHEREORDER中检查两次条件或制作可能昂贵的UNION?

请解释这是什么问题(如果有的话)?

select * 
from temp 
order by case 
when a > 0 and b > 0 then 1 
when a > 0 or b > 0 then 2 
else 0 
end 

只要用你的case,然后按子句顺序结束逻辑(不使用"priority"别名)。

这是一个演示

那么这个对你来说应该没问题:

select * --to select all
from temp --from your table
where (a > 0 or b > 0) --where a or b is bigger than 0 because this is the same as your case when then end example
order by case --I have used your logic for order by clause
when a > 0 and b > 0 then 1 
when a > 0 or b > 0 then 2 
else 0 
end

这是第二个演示

这是OP建议的第三个选项:

select *
from temp 
where (a > 0 or b > 0)
order by case 
when a > 0 and b > 0 then 0
else 1
end

这是第三个演示

最新更新