如果我在 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)