简体   繁体   中英

SQL select all rows where at least one column is not NULL

Im looking for a best way to select all rows where at least one of these column

job_start, title, visit_hours, name, leave_start and leave_end

has a value, and at least one uniq first_name row must be selected from below table

The result should exclude row 1 and 7

在此处输入图片说明

using row_number() to return at least 1 row per first_name , prioritizing those with a non- null column first.

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
  )

In Postgres, you can do this using 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)

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