SQL 如何首先返回具有特定值的行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1250156/
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 do I return rows with a specific value first?
提问by Phoexo
I want my query to return the rows of the table where a column contains a specific value first, and then return the rest of the rows alphabetized.
我希望我的查询返回表的行,其中列首先包含特定值,然后返回按字母顺序排列的其余行。
If I have a table something like this example:
如果我有一个类似于这个例子的表:
- Table: Users
- id - name - city
- 1 George Seattle
- 2 Sam Miami
- 3 John New York
- 4 Amy New York
- 5 Eric Chicago
- 6 Nick New York
And using that table I want to my query to return the rows which contain New York first, and then the rest of the rows alphabetized by city. Is this possible to do using only one query?
使用该表,我希望我的查询首先返回包含纽约的行,然后返回按城市字母顺序排列的其余行。仅使用一个查询就可以做到这一点吗?
回答by Rob Farley
On SQL Server, Oracle, DB2, and many other database systems, this is what you can use:
在 SQL Server、Oracle、DB2 和许多其他数据库系统上,您可以使用以下方法:
ORDER BY CASE WHEN city = 'New York' THEN 1 ELSE 2 END, city
回答by chaos
If your SQL dialect is intelligent enough to treat boolean expressions as having a numeric value, then you can use:
如果您的 SQL 方言足够智能,可以将布尔表达式视为具有数值,那么您可以使用:
SELECT *
FROM `Users`
ORDER BY (`city` = 'New York') DESC, `city`
回答by Manjuboyz
My answer may be old and not required but someone may need different approach,hence posting it here.
我的答案可能是旧的,不是必需的,但有人可能需要不同的方法,因此将其张贴在这里。
I had same requirement implemented this, worked for me.
我有同样的要求实现了这个,对我有用。
Select * from Users
ORDER BY
(CASE WHEN city = 'New York' THEN 0 ELSE 1 END), city
GO
PS
聚苯乙烯
this is for SQL
这是用于SQL