简体   繁体   中英

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. Any help will be greatly appreciated. Thanks

You can:

  1. Order rows by number of nulls (ascending)
  2. Limit rows to 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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