Postgres - DISTINCT ON 是否优先选择列中的非空值



如果我在 2 列上使用 DISTINCT ON,并且有第三列可以具有空值,DISTINCT ON是否总是尝试返回第三列不为 null 的行,还是只是下降到ORDER BY

例如,对于此表:

col1    col2   col3
1       88     8
1       88     9
1       88     1
2       88     3 
2       88
3       88

我希望能够SELECT DISTINCT ON (col1, col2)并获取col3不为空的行,除非DISTINCT ON (col1, col2)没有col3不为空的行。

它完全基于您ORDER BY的内容。如果您想首选带有非NULL col3的行,只需将其包含在您的排序中:

SELECT DISTINCT ON (col1, col2) ... ORDER BY col1, col2, col3 ASC NULLS LAST .

select distinct col1, col2, col3
from table t
where t.col3 is not null
 or not exists(select 1 from table tt 
    where tt.col1 = t.col1 and tt.col2 = t.col2 and tt.col3 is not NULL)

最新更新