开发者

Conditional ORDER BY depending on column values

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 Impor开发者_如何学编程t ID (Last one first), and return that row. Or else, just return the top 1 row from the original query.


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) 


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;


I used in Firebird (columns are numeric):

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜