基于大多数行的分配顺序在mysql数据库中不为空

Posted

技术标签:

【中文标题】基于大多数行的分配顺序在mysql数据库中不为空【英文标题】:Assign order based on most rows are not null in mysql database 【发布时间】:2020-07-20 10:14:21 【问题描述】:

我正在为变量生成所有组合并插入到临时表中

select *
from (select 33 as age union all select null) a cross join
     (select 44 as totaldd union all select null) t cross join
     (select 30 as timeperiod union all select null) d cross join
     (select CURDATE() as StartDateTime union all select null) s

结果是:

我希望基于大多数行的顺序不为空 Like

【问题讨论】:

【参考方案1】:

如果您运行的是 mysql 8.0,您可以使用 dense_rank() 和条件表达式来执行此操作:

select 
    a.age, 
    t.totaldd, 
    d.timeperiod, 
    s.startdatetime,
    dense_rank() over(order by 
          (a.age is null) 
        + (t.totaldd is null) 
        + (d.timeperiod is null) 
        + (s.startdatetime is null)
    ) as rn
from (select 33 as age union all select null) a cross join
     (select 44 as totaldd union all select null) t cross join
     (select 30 as timeperiod union all select null) d cross join
     (select CURDATE() as startdatetime union all select null) s

实际上你甚至可以不使用窗口函数,只使用条件表达式:

select 
    a.age, 
    t.totaldd, 
    d.timeperiod, 
    s.startdatetime,
    1 + (a.age is null) 
        + (t.totaldd is null) 
        + (d.timeperiod is null) 
        + (s.startdatetime is null) as rn
from (select 33 as age union all select null) a cross join
     (select 44 as totaldd union all select null) t cross join
     (select 30 as timeperiod union all select null) d cross join
     (select CURDATE() as startdatetime union all select null) s

【讨论】:

以上是关于基于大多数行的分配顺序在mysql数据库中不为空的主要内容,如果未能解决你的问题,请参考以下文章

如何组合多行数据,直到下一行值在 SQL Server 中不为空

数据库SQL语句查询表中不为空的字段的数量为5的SQL语句?

选择 mongoid 中不为空或为空的位置

检查指针在析构函数中不为空[重复]

如果它们在 Python 中不为空,则连接多个字符串

如果 itemsource 中不存在值,则组合框分配 null