gpt4 book ai didi

sql - Oracle 相当于 Postgres 的 DISTINCT ON?

转载 作者:行者123 更新时间:2023-11-29 11:08:29 25 4
gpt4 key购买 nike

在 postgres 中,您可以使用 DISTINCT ON 查询组中的第一个值。 这在 Oracle 中如何实现?

来自 postgres 手册:

SELECT DISTINCT ON ( expression [, ...] ) keeps only the first row of each set of rows where the given expressions evaluate to equal. The DISTINCT ON expressions are interpreted using the same rules as for ORDER BY (see above). Note that the "first row" of each set is unpredictable unless ORDER BY is used to ensure that the desired row appears first.

例如,对于给定的表:

 col1 | col2 
------+------
A | AB
A | AD
A | BC
B | AN
B | BA
C | AC
C | CC

升序排序:

> select distinct on(col1) col1, col2 from tmp order by col1, col2 asc;
col1 | col2
------+------
A | AB
B | AN
C | AC

降序:

> select distinct on(col1) col1, col2 from tmp order by col1, col2 desc;
col1 | col2
------+------
A | BC
B | BA
C | CC

最佳答案

通过使用 first_value() 可以在 Oracle 中复制相同的效果功能或使用 rank() 之一或 row_number() 功能。

这两种变体也适用于 Postgres。

first_value()

select distinct col1, 
first_value(col2) over (partition by col1 order by col2 asc)
from tmp

first_value给出分区的第一个值,但对每一行重复它,因此有必要将它与 distinct 结合使用为每个分区获取一行。

row_number()/rank()

select col1, col2 from (
select col1, col2,
row_number() over (partition by col1 order by col2 asc) as rownumber
from tmp
) foo
where rownumber = 1

替换 row_number()rank()在这个例子中产生相同的结果。

此变体的一个特点是它可以用于获取给定分区的前 N 行(例如,“最后 3 个更新”),只需更改 rownumber = 1 即可。至 rownumber <= N .

关于sql - Oracle 相当于 Postgres 的 DISTINCT ON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10515391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com