I have a load of rules about how a result set must be ordered. I need to use a CASE to work out the columns to order by.
I am trying this:
ORDER BY
CASE
WHEN ISNULL(actual_appearance_date, scheduled_appearance_date) IS NOT NULL AND icbm.emma_id IS NOT NULL -- We have it all!
THEN ISNULL(actual_appearance_date, scheduled_appearance_date) DESC , icbm.emma_id , version_number , icaci_t.[ijis_court_appearance_court_item_tracker_id]
WHEN ISNULL(actual_appearance_date, scheduled_appearance_date) IS NOT NULL AND icbm.emma_id IS NULL -- We have an appearance date, but it's manual.
THEN ISNULL(actual_appearance_date, scheduled_appearance_date) DESC, icaci_t.[ijis_court_appearance_court_item_tracker_id] DESC
WHEN ISNULL(actual_appearance_date, scheduled_appearance_date) IS NULL AND icbm.emma_id IS NOT NULL -- No appearance date, but it has a Business Message
THEN icbm.emma_id DESC, version_number DESC, icaci_t.[ijis_court_appearance_court_item_tracker_id] DESC
ELSE icaci_t.[ijis_court_appearance_court_item_tracker_id] DESC -- No Appearance date, not Message.
END
But it seems I can only include one column after the THEN. But I need tio use a few columns, based on my rules.
Is there a way to do this?
To order a result set by diferent rules on different rows does not really make sense, as the conflicting rules will create inconsistencies in how individual orderings between rows are made. In other words there is no consistent ordering if the ordering rules are inconsistent.
However I suspect you are making this issue much more complicated than it needs to be. I suspect you can just order by:
The NULL values will sort themselves out and be sorted together. Perhaps start from here and figure out what needs to change.