简体   繁体   English

如何使用case语句对数据进行排序-使用MySQL?

[英]How to sort data with a case statement - using MySQL?

I have a query but I want to order the data as the following: 我有一个查询,但我想按以下顺序订购数据:

  1. status (so I have the records with status = 1 on the top and status 2 at the bottom) 状态(所以我的记录顶部为状态= 1,底部为状态2)

  2. if the records have status = 1 then order them as the following 如果记录的status = 1则按以下顺序对其进行排序
    a) CASE WHEN i.assigned_to = '.USER_ID.' THEN 0 ELSE 1 END a) CASE WHEN i.assigned_to = '.USER_ID.' THEN 0 ELSE 1 END CASE WHEN i.assigned_to = '.USER_ID.' THEN 0 ELSE 1 END
    b) CASE WHEN (i.approved_by > 0 OR i.approved_on IS NOT NULL) THEN 0 ELSE 1 END b) CASE WHEN (i.approved_by > 0 OR i.approved_on IS NOT NULL) THEN 0 ELSE 1 END
    c) i.priority DESC c) i.priority DESC
    d) i.created_on ASC d) i.created_on ASC

  3. if the records have status = 2 then order the records by completed_on DESC 如果记录的status = 2completed_on DESC对记录进行排序

This is my current syntax but I can't figure out how to split the order 这是我目前的语法,但我不知道如何拆分订单

ORDER BY
  i.status ASC,
  CASE WHEN i.assigned_to = '.USER_ID.' THEN 0 ELSE 1 END,
  CASE WHEN (i.approved_by > 0 OR i.approved_on IS NOT NULL) THEN 0 ELSE 1 END,
  i.priority DESC,
  i.created_on ASC

My query currently order all the records by a) CASE WHEN i.assigned_to = '.USER_ID.' 我的查询当前通过以下方式对所有记录进行排序:a)i.assigned_to ='.USER_ID'时的情况。 THEN 0 ELSE 1 END b) (CASE WHEN (i.approved_by > 0 OR i.approved_on IS NOT NULL) THEN 0 ELSE 1 END) c) i.priority DESC d) i.created_on ASC THEN 0 ELSE 1 END b)(当(i.approved_by> 0或i.approved_on不为空)的情况THEN 0 ELSE 1 END)c)i.priority DESC d)i.created_on ASC

and I want it to order by those only if the status = 1 otherwise order by completed_on DESC 我只希望status = 1时才按那些排序,否则按completed_on DESC排序

Try: 尝试:

ORDER BY
  i.status ASC,
  CASE WHEN i.assigned_to = '.USER_ID.' and i.status = 1 THEN 0 ELSE 1 END,
  CASE WHEN (i.approved_by > 0 OR i.approved_on IS NOT NULL) and i.status = 1 
       THEN 0 ELSE 1 END,
  CASE WHEN i.status = 1 THEN i.priority END DESC,
  CASE WHEN i.status = 1 THEN i.created_on END ASC,
  CASE WHEN i.status = 2 THEN i.completed_on END DESC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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