排序并返回具有最大非空值列的行 - MYSQL

时间:2016-10-11 12:00:20

标签: mysql database

我已经搜索了Google,Stackoverflow和其他众多网站2天了。我无法想出它的逻辑。

我有5列。

col1 |col2  |col3  |col4  |  col5
2000 | null | 1000 | null | null
5000 | 1000 | null | null | null
null | null | null | null | null
1000 | 100  | 250  | 600  | 111
4000 | 400  | 350  | null | 111

对不起上面乱糟糟的表格。仍然是stackoverflow的新功能。

现在,我想写一个选择查询,它将执行以下操作:
1)以这样的方式排列这5行,使得具有最大非空值的行将首先出现。并且,逐渐地以一行最大空值结束 2)不返回所有列都为空的行。

对于上面的例子,我们首先得到row4然后是row5然后是row1然后是row2。请注意,不返回row3,因为所有值都为null。

直到现在我已经尝试了下面的查询已接近解决它,但不够准确。

SELECT * 
FROM   table 
WHERE  col1 IS NOT NULL 
        OR col2 IS NOT NULL 
        OR col3 IS NOT NULL 
        OR col4 IS NOT NULL 
        OR col5 IS NOT NULL 
ORDER  BY CASE 
            WHEN col1 IS NULL THEN 1 
            ELSE 0 
          END, 
          col1 DESC, 
          CASE 
            WHEN col2 IS NULL THEN 1 
            ELSE 0 
          END, 
          col2 DESC, 
          CASE 
            WHEN col3 IS NULL THEN 1 
            ELSE 0 
          END, 
          col3 DESC, 
          CASE 
            WHEN col4 IS NULL THEN 1 
            ELSE 0 
          END, 
          col4 DESC, 
          CASE 
            WHEN col5 IS NULL THEN 1 
            ELSE 0 
          END, 
          col5 DESC 

3 个答案:

答案 0 :(得分:2)

最简单的方法是计算空值的数量:

select t.*
from t
where (col1 is not null) or (col2 is not null) or (col3 is not null) or
      (col4 is not null) or (col5 is not null)
order by (col1 is not null) + (col2 is not null) + (col3 is not null) +
         (col4 is not null) + (col5 is not null);

这使用MySQL快捷方式将布尔值视为整数。

答案 1 :(得分:1)

您可以使用NULL计算IF个值字段的数量:

SELECT *
FROM (
   SELECT *,
          IF(col1 IS NULL, 1, 0) +  IF(col2 IS NULL, 1, 0) +
          IF(col3 IS NULL, 1, 0) +  IF(col4 IS NULL, 1, 0) +
          IF(col5 IS NULL, 1, 0) AS count_nulls
   FROM table) AS t
WHERE t.count_nulls < 5 
ORDER BY t.count_nulls

Demo here

答案 2 :(得分:1)

SELECT col1, 
       col2, 
       col3, 
       col4, 
       col5, 
       Sum(col1 + col2 + col3 + col4 + col5) AS total 
WHERE  col1 IS NOT NULL 
       AND col2 IS NOT NULL 
       AND col3 IS NOT NULL 
       AND col4 IS NOT NULL 
       AND col5 IS NOT NULL 
ORDER  BY total