How do I return rows with a specific value first?

ぃ、小莉子 提交于 2019-11-26 06:16:07

问题


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?


回答1:


On SQL Server, Oracle, DB2, and many other database systems, this is what you can use:

ORDER BY CASE WHEN city = 'New York' THEN 1 ELSE 2 END, city



回答2:


If your SQL dialect is intelligent enough to treat boolean expressions as having a numeric value, then you can use:

SELECT *
FROM `Users`
ORDER BY (`city` = 'New York') DESC, `city`



回答3:


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



来源:https://stackoverflow.com/questions/1250156/how-do-i-return-rows-with-a-specific-value-first

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!