我正在寻找一种最佳方式来选择至少其中一列
的所有行job_start, title, visit_hours, name, leave_start and leave_end
有一个值,并且必须从下表
中选择至少一个uniq first_name行结果应排除第1行和第7行
答案 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)