【发布时间】:2020-12-29 18:30:10
【问题描述】:
我注意到在 PostgreSQL 中以下两个查询输出不同的结果:
select a.*
from (
select distinct on (t1.col1)
t1.*
from t1
order by t1.col1, t1.col2
) a
where a.col3 = value
;
create table temp as
select distinct on (t1.col1)
t1.*
from t1
order by t1.col1, t1.col2
;
select temp.*
from temp
where temp.col3 = value
;
我猜这与在子查询中使用 distinct on 有关。
在子查询中使用distinct on 的正确方法是什么?例如。如果我不使用where 语句,我可以使用它吗?
或者像
(
select distinct on (a.col1)
a.*
from a
)
union
(
select distinct on (b.col1)
b.*
from b
)
【问题讨论】:
-
请提供一个最小可重复的例子:样本数据和期望的结果,作为表格文本。
-
恕我直言,两者都应该返回相同的结果。
标签: sql postgresql sql-order-by distinct greatest-n-per-group