gpt4 book ai didi

sql - postgresql 计算前 3 行

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

我知道我们可以在 PostreSQL 中使用 LIMIT 来获取关系中的前 3 个值,但是如果存在重复值怎么办。例如,5个4个4个3个2

按降序排列并使用 LIMIT 3 将只返回 5,4,4。但是我们如何得到 5,4,4,3(重复的前 3 个)。

我知道如何在很长的时间内做到这一点,但我想知道是否有任何内置的 PostreSQL?

最佳答案

一种简单的方法是使用 dense_rank window function根据需要对值进行排名,然后剥离具有所需排名的值。

例如,给定这个:

create table t (
id serial not null primary key, -- just a placeholder so that we can differentiate the duplicate `c`s.
c int not null
);
insert into t (c)
values (1), (1), (2), (3), (4), (4), (4), (5);

您可能想要带有 c 的行在(5,4,3)你可以这样做:

select id, c
from (
select id, c, dense_rank() over (order by c desc) as r
from t
) dt
where r <= 3

演示:http://sqlfiddle.com/#!15/5b262/8

注意需要使用dense_rank而不是 rank因为rank会按正确的顺序排列事物,但会在排名中留下空白所以r <= 3不一定有效。比较 r上面的值摆弄 dense_rankrank你会看到不同之处。

关于sql - postgresql 计算前 3 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35954697/

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