Conditional ORDER BY depending on column values

谁说胖子不能爱 提交于 2019-12-01 21:18:34

问题


I need to write a query that does this:

SELECT TOP 1 
FROM a list of tables (Joins, etc)
ORDER BY Column X, Column Y, Column Z

If ColumnX is NOT NULL, then at the moment, I reselect, using a slightly different ORDER BY.

So, I do the same query, twice. If the first one has a NULL in a certain column, I return that row from my procedure. However, if the value isn't NULL - I have to do another identical select, except, order by a different column or two.

What I do now is select it into a temp table the first time. Then check the value of the column. If it's OK, return the temp table, else, redo the select and return that result set.

More details:

In english, the question I am asking the database:

Return my all the results for certain court appearance (By indexed foreign key). I expect around 1000 rows. Order it by the date of the appearance (column, not indexed, nullable), last appearance first. Check an 'importId'. If the import ID is not NULL for that top 1 row, then we need to run the same query - but this time, order by the Import ID (Last one first), and return that row. Or else, just return the top 1 row from the original query.


回答1:


I'd say the BEST way to do this is in a single query is a CASE statement...

SELECT TOP 1 FROM ... ORDER BY 
    (CASE WHEN column1 IS NULL THEN column2 ELSE column1 END) 



回答2:


You could use a COALESCE function to turn nullable columns into orderby friendly values.

 SELECT   CAST(COALESCE(MyColumn, 0) AS money) AS Column1 
 FROM     MyTable
 ORDER BY Column1;



回答3:


I used in Firebird (columns are numeric):

ORDER BY CASE <condition> WHEN <value> THEN <column1>*1000 + <column2> ELSE <column3>*1000 + <column4> END


来源:https://stackoverflow.com/questions/7464434/conditional-order-by-depending-on-column-values

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