SQL选择至少一列不为NULL的所有行

时间:2017-10-31 23:08:32

标签: sql postgresql

我正在寻找一种最佳方式来选择至少其中一列

的所有行
job_start, title, visit_hours, name, leave_start and leave_end

有一个值,并且必须从下表

中选择至少一个uniq first_name行

结果应排除第1行和第7行

enter image description here

2 个答案:

答案 0 :(得分:1)

使用row_number()first_name至少返回1行,优先考虑非null列的行。

select *
from (
  select t.*
    , row_number() over (
        partition by first_name 
        order by case when job_start is not null
                or title is not null
                or visit_hours is not null
                or name is not null
                or leave_start is not null
                or leave_end is not null
          then 0 
          else 1 
          end
        ) as rn
  from t
) sub
where rn = 1
  or (job_start is not null
    or title is not null
    or visit_hours is not null
    or name is not null
    or leave_start is not null
    or leave_end is not null
  )

答案 1 :(得分:0)

在Postgres中,您可以使用distinct on

执行此操作
select distinct on (first_name) t.*
from t
order by first_name,
         (case when job_start is not null or
                    title is not null or
                    visit_hours is not null or
                    name is not null or
                    leave_start is not null or
                    leave_end is not null
               then 0 
               else 1 
          end)