MySQL - 按日期排序ASC和DESC,具体取决于其他领域

时间:2014-05-28 13:31:15

标签: mysql

我在表格中有这些行......

id  task_type   task_date
1   1           01/15/2010
2   2           01/18/2010
3   1           01/18/2010
4   2           01/16/2010
6   1           01/16/2010
8   1           01/17/2010
9   2           01/17/2010

我希望以特定的方式对它们进行排序:当ASC的task_type = 1顺序和DESC的task_type = 2 order时

id  task_type   task_date
1   1           01/15/2010
6   1           01/16/2010
8   1           01/17/2010
3   1           01/18/2010
2   2           01/18/2010
9   2           01/17/2010
4   2           01/16/2010

这甚至可能吗?我一直在寻找条件查询,我所能得到的只是语法错误...

这是我无法正常运行的查询:

SELECT id, task_type, task_date 
From Tasks
ORDER BY CASE WHEN task_type=1  THEN
task_type ASC, task_date ASC, hour ASC, priority DESC, id ASC 
WHEN task_type=2 THEN
task_type ASC, task_date DESC, hour ASC, priority DESC, id ASC 
END

1 个答案:

答案 0 :(得分:1)

我不确定estado是什么,但你的逻辑似乎是:

ORDER BY task_type,
         (CASE WHEN task_type = 1 THEN task_date END) ASC,
         (CASE WHEN task_type = 1 THEN hour END) ASC,
         (CASE WHEN task_type = 1 THEN priority END) DESC,
         (CASE WHEN task_type = 1 THEN id END) ASC,
         (CASE WHEN task_type = 2 THEN task_date END) DESC,
         (CASE WHEN task_type = 2 THEN hour END) ASC,
         (CASE WHEN task_type = 2 THEN priority END) DESC,
         (CASE WHEN task_type = 2 THEN id END) ASC

这可以简化为:

ORDER BY task_type,
         (CASE WHEN task_type = 1 THEN task_date END) ASC,
         (CASE WHEN task_type = 2 THEN task_date END) DESC,
         hour ASC, priority DESC, id ASC