是否可以对每行的列进行排序?

时间:2017-11-08 06:35:16

标签: mysql sorting

我有一张桌子:

create table SomeTable( 
    N1 int(11) not null default 0,
    N2 int(11) not null default 0,
    N3 int(11) not null default 0,
    N4 int(11) not null default 0,
    N5 int(11) not null default 0
)

该表只有一行,如下所示:

N1 : 1
N2 : 2
N3 : 5
N4 : 0
N5 : 3

当我查询select * from table时,我得到:

N1, N2, N3, N4, N5
 1,  2,  5,  0,  3

是否可以对此类数据进行排序?

N3, N5, N2, N1, N4
 5,  3,  2,  1,  0

2 个答案:

答案 0 :(得分:0)

不幸的是,你不能这样做你可以订购行但不能订购列...你可以像这样指定所选列的顺序:

select N3, N5, N2, N1, N4 from SomeTable

答案 1 :(得分:0)

您无法动态影响列名称,但您可以订购值:

select
    greatest(N1, N2, N3, N4, N5) as col1,
    case greatest(N1, N2, N3, N4, N5)
        when N1 then greatest(N2, N3, N4, N5) 
        when N2 then greatest(N1, N3, N4, N5) 
        when N3 then greatest(N1, N2, N4, N5) 
        when N4 then greatest(N1, N2, N3, N5) 
        when N5 then greatest(N1, N2, N3, N4)
    end as col2,
    case greatest(N1 + N2, N1 + N3, N1 + N4, N1 + N5, N2 + N3, N2 + N4, N2 + N5, N3 + N4, N3 + N5, N4 + N5)
        when N1 + N2 then greatest(N3, N4, N5) 
        when N1 + N3 then greatest(N2, N4, N5)
        when N1 + N4 then greatest(N2, N3, N5)
        when N1 + N5 then greatest(N2, N3, N4)
        when N2 + N3 then greatest(N1, N4, N5)
        when N2 + N4 then greatest(N1, N3, N5)
        when N2 + N5 then greatest(N1, N3, N4)
        when N3 + N4 then greatest(N1, N2, N5)
        when N3 + N5 then greatest(N1, N2, N4)
        when N4 + N5 then greatest(N1, N2, N3)
    end as col3,
    case least(N1, N2, N3, N4, N5)
        when N1 then least(N2, N3, N4, N5) 
        when N2 then least(N1, N3, N4, N5) 
        when N3 then least(N1, N2, N4, N5) 
        when N4 then least(N1, N2, N3, N5) 
        when N5 then least(N1, N2, N3, N4)
    end as col4,
    least(N1, N2, N3, N4, N5) as col5
from table

这将适用于表格中的任意数量的行(不仅仅是您的情况下的1行)。