Conditional ORDER BY depending on column values

2019-02-23 21:09发布

问题:

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;