[英]SQL special sort order under certain circumstances
I have the following scenario: 我有以下场景:
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). open
和customerResponded
具有相同的优先级,因此这些项目按最新票证消息ASC的日期时间排序(应首先处理最长的未触摸票证,因此在列表顶部)。 waitingForCustomer
has a lower priority. waitingForCustomer
的优先级较低。 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). waitingForCustomer
总是落后于状态为open
或customerResponded
票证,并且这些票据按日期时间DESC排序(因为客户从未回复的旧票证不太相关)。 closed
works the same as waitingForCustomer
but has an even lower priority, so those tickets are at the end of list. closed
工作方式与waitingForCustomer
相同,但优先级更低,因此这些工单位于列表的末尾。 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? 是否可以向ORDER BY添加条件以使这样的事情成为可能,或者是否有其他方法来实现它?
Edit: The ticket status is an integer (open = 0, customerResponded = 10, waitingForCustomer = 20, closed = 100). 编辑:故障单状态是一个整数(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: 感谢GarethD,我找到了一个解决方案,但与他的有点不同:
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
. 首先,我检查我的状态是
open=0
还是customerResponded=10
。
If so, I order by 0 (which means just equally on top of the list). 如果是这样,我按0排序(这意味着同样在列表的顶部)。
Else, I order by the ticket status ( waitingForCustomer
has higher priority than closed
). 否则,我按票证状态排序(
waitingForCustomer
优先级高于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". 从属订单指令现在通过
message_created ASC
或-message_created ASC
(技术上是message_created DESC
)按顺序在下级“组”中按日期排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.