简体   繁体   中英

SQL special sort order under certain circumstances

I have the following scenario:

  • I have a list with support tickets
  • Every support ticket has a number of messages (with own datetimes)
  • Every ticket has a status (open, customerResponded, waitingForCustomer, closed)

The whole table should be sorted by a fictional priority, which means:

  • open and customerResponded have the same priority, so these items are sorted by the datetime of the latest ticket message ASC (longest untouched ticket should be processed first, so on top of list).
  • waitingForCustomer has a lower priority. So tickets with waitingForCustomer are always behind ones with the status open or customerResponded , and those are sorted by datetime DESC (since a old ticket a customer never replied to is less relevant).
  • closed works the same as waitingForCustomer but has an even lower priority, so those tickets are at the end of list.

So, after I explained the scenario, I have the following question:

Is it possible to add conditions to ORDER BY to make something like that possible, or is there any other way to implement that?

Edit: The ticket status is an integer (open = 0, customerResponded = 10, waitingForCustomer = 20, closed = 100).

You can just use a case expression inside your order by:

ORDER BY status,
        CASE WHEN status IN (0, 10) THEN Datetime END ASC,
        CASE WHEN status IN (20, 100) THEN Datetime END DESC

Thank's to GarethD, I found a solution, which is but a bit different from his:

ORDER BY
    CASE WHEN t.`ticket_status` IN (0, 10) THEN 0 ELSE t.`ticket_status` END ASC,
    CASE WHEN t.`ticket_status` IN (0, 10) THEN m.`message_created`
                                           ELSE -m.`message_created` END ASC

First of all, I check whether I have the status open=0 or customerResponded=10 .

If so, I order by 0 (which means just equally on top of the list).

Else, I order by the ticket status ( waitingForCustomer has higher priority than closed ).

The subordinate order instruction now orders by message_created ASC or by -message_created ASC (which is technically message_created DESC ) to order by date correctly in the subordinate "group".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM