oracle 如何在 SQL 查询中设置条件逻辑以调整优先级?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2414206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set conditional logic in SQL query in order to shuffle the precedence?
提问by Roman Kagan
How to set conditional logic in SQL query in order to shuffle the precedence?
如何在 SQL 查询中设置条件逻辑以调整优先级?
For example if I have table with columns like "id", "name", "event_id" and I have distinct "event_id" like 180, 181, 270, 271 and I need to order in such a way that rows with "event_id" 270 will be at the top, then rows with "even_id" 271 and the rest of the data will be ordered by "id" column in descending order.
例如,如果我有包含“id”、“name”、“event_id”等列的表,并且我有不同的“event_id”,如 180、181、270、271,我需要以这样一种方式排序,即带有“event_id”的行270 将在顶部,然后带有“even_id” 271 的行和其余数据将按“id”列降序排列。
回答by zerkms
use CASE statement to do order you want
使用 CASE 语句来做你想要的订单
ORDER BY
CASE
WHEN event_id = 270 THEN 0
WHEN event_id = 271 THEN 1
ELSE 2
END,
id DESC
回答by Jeffrey Kemp
I prefer CASE:
我更喜欢案例:
ORDER BY CASE event_id WHEN 270 THEN 0
WHEN 271 THEN 1
END NULLS LAST,
id DESC;
but sometimes I use DECODE which is a little less wordy:
但有时我会使用 DECODE,这有点不那么冗长:
ORDER BY DECODE(event_id, 270, 0,
271, 1,
2),
id DESC;
回答by Marcus Adams
Here's a simple way if you only have one case:
如果您只有一个案例,这是一种简单的方法:
ORDER BY event_id <> 270 ASC, event_id ASC
The expression event_id <> 270
evaluates to 0 for false or 1 for true.
该表达式的event_id <> 270
计算结果为 0 表示假或 1 表示真。