簡體   English   中英

使用 NULL 對多個文本列進行排序

[英]Sort multiple text columns with NULL

我有以下幾列:

a    | null
x    | f
null | a
i    | n

我需要兩列按字母順序排序,底部為空值,如下所示:

a    | a
i    | f
x    | n
null | null

無論如何在mysql中做到這一點?

每一列必須相互獨立排序,然后按每個值的位置按該順序重新組合行。
使用ROW_NUMBER()窗口函數:

select t1.col1, t2.col2
from (
  select col1, row_number() over(order by col1 is null, col1) rn
  from tablename
) t1 inner join (  
  select col2, row_number() over(order by col2 is null, col2) rn
  from tablename
) t2 on t2.rn = t1.rn

請參閱演示

或者使用 CTE:

with
  cte1 as (select col1, row_number() over(order by col1 is null, col1) rn from tablename),
  cte2 as (select col2, row_number() over(order by col2 is null, col2) rn from tablename)
select cte1.col1, cte2.col2
from cte1 inner join cte2 
on cte2.rn = cte1.rn

請參閱演示

結果:

| col1 | col2 |
| ---- | ---- |
| a    | a    |
| i    | f    |
| x    | n    |
| null | null |

要獨立訂購 2 列,最后使用空值?

對於 MySql 5.x,這里有一個按 π 排序的解決方案:

-- sample data
drop table if exists test;
create table test (col1 varchar(8), col2 varchar(8));
insert into test (col1, col2) values
('a', null), ('x', 'f'), (null, 'a'), ('i', 'n');

-- initiating variables
set @rn1:=0, @rn2:=0;
-- query that links on calculated rownumbers
select col1, col2
from (select @rn1:=@rn1+1 as rn, col1 from test order by coalesce(col1,'π') asc) q1
left join (select @rn2:=@rn2+1 as rn, col2 from test order by coalesce(col2,'π') asc) q2
  on q1.rn = q2.rn
order by q1.rn;

結果:

col1    col2
a       a
i       f
x       n
NULL    NULL

在 MySql 8.0 中,可以使用窗口函數ROW_NUMBER代替變量。

select col1, col2
from (select row_number() over (order by coalesce(col1,'π') asc) as rn, col1 from test) q1
left join (select row_number() over (order by coalesce(col2,'π') asc) as rn, col2 from test where col2 is not null) q2
  on q1.rn = q2.rn
order by q1.rn;

db<>fiddle 的測試在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM