PostgreSQL 查询列上空值最少的行

PostgreSQL query rows with least null value on columns

如何查询输出为列中空值最少的行的行?

我的数据是:

ID         | col1     | col2      | col3      | col4     
-----------+----------+-----------+-----------+-----------
 1         | Null     |Null       | with value| with value
 2         |with value|Null       | with value| with value
 3         |with value|Null       | Null      | Null       

结果将是:

 ID         | col1     | col2      | col3      | col4     
 -----------+----------+-----------+-----------+-----------
  2         |with value|Null       | with value| with value  

因为 id 2 是空值最少的记录。 任何帮助将不胜感激。谢谢

您可以:

  1. 按空值数(升序)对行进行排序
  2. 行数限制为 1 (LIMIT 1)

您的代码:

SELECT *
FROM your_table
ORDER BY 
    CASE WHEN col1 IS NULL THEN 1 ELSE 0 END +
    CASE WHEN col2 IS NULL THEN 1 ELSE 0 END +
    CASE WHEN col3 IS NULL THEN 1 ELSE 0 END +
    CASE WHEN col4 IS NULL THEN 1 ELSE 0 END 
LIMIT 1

如果你只想要一行,那么你可以这样做:

select t.*
from t
order by ( (col1 is null)::int + (col2 is null)::int +
           (col3 is null)::int + (col4 is null)::int
         ) asc
fetch first 1 row only;

如果你想要所有这样的行,我想我会这样做:

select t.*
from (select t.*,
             dense_rank() over 
                 (order by (col1 is null)::int + (col2 is null)::int +
                           (col3 is null)::int + (col4 is null)::int
                 ) as null_ranking
      from t
     ) t
where null_ranking = 1;