简体   繁体   English

PostgreSQL查询列上具有最少空值的行

[英]PostgreSQL query rows with least null value on columns

How can I query rows where the output would be the rows with least null value on the columns?如何查询输出将是列上具有最少空值的行的行?

My data is:我的数据是:

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       

where the result would be:结果是:

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

Because id 2 is the record with fewest null values.因为 id 2 是空值最少的记录。 Any help will be greatly appreciated.任何帮助将不胜感激。 Thanks谢谢

You can:你可以:

  1. Order rows by number of nulls (ascending)按空值的数量对行进行排序(升序)
  2. Limit rows to 1 ( LIMIT 1 )将行限制为 1 ( LIMIT 1 )

Your code:您的代码:

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

If you want only one row, then you can do:如果你只想要一行,那么你可以这样做:

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;

If you want all such rows, I think I would do:如果你想要所有这样的行,我想我会这样做:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM