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

时间:2019-01-08 08:01:35

标签: sql postgresql top-n

如何查询行,其中输出将是列中具有最小null值的行?

我的数据是:

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是具有最少空值的记录。 任何帮助将不胜感激。谢谢

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

如果只需要一行,则可以执行以下操作:

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;