有条件地在SQL中更改排序方向

时间:2017-09-22 00:37:12

标签: mysql sorting

我对a similar question that was asked many years ago on StackOverflow

有一个有趣的看法

为简单起见,假设我有一个包含三列的表:

+----+------+-------+
| id | cond | value |
+----+------+-------+
| 1  |  1   |  "A"  |
| 2  |  0   |  "B"  |
| 3  |  1   |  "C"  |
| 4  |  0   |  "D"  |
| 5  |  1   |  "E"  |
+----+------+-------+

现在我想先按cond排序此表,然后按value 升序 排序,如果cond为0且<如果cond为1,则强> 降序 。最终排序表应如下所示:

+----+------+-------+
| id | cond | value |
+----+------+-------+
| 2  |  0   |  "B"  |
| 4  |  0   |  "D"  |
| 5  |  1   |  "E"  |
| 3  |  1   |  "C"  |
| 1  |  1   |  "A"  |
+----+------+-------+

请注意,我不能依赖value来计算数字,所以我不能做一些聪明的事情:

order by cond, (case when cond = 0 then value else -value end)

2 个答案:

答案 0 :(得分:3)

使用两个分开的条件cond来排序结果:

select *
from yourtable
order by 
    cond, 
    case when cond = 0 then `value` else 1 end,
    case when cond = 1 then `value` else 1 end desc

请在此处查看 SQLFiddle DEMO

答案 1 :(得分:1)

按值排序后添加行号。然后进行条件排序:

select *
from (
  select a.*, @r := @r + 1 AS rn
  from (
    select *
    from mytable
    order by value) a
  join (select @r := 0) b) a
order by cond, (case when cond then -rn else rn end)

将排序转换为int的另一种方法:

select a.*, count(b.id) c
from mytable a
join mytable b on a.cond = b.cond and a.value > b.value
group by a.id
order by a.cond, case when a.cond then -c else c end