【问题标题】:postgresql count the top 3 rowspostgresql 计算前 3 行
【发布时间】:2016-03-12 06:51:51
【问题描述】:

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

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

我知道如何做到这一点,但我想知道是否有内置的 PostreSQL?

【问题讨论】:

    标签: sql postgresql greatest-n-per-group


    【解决方案1】:

    一种简单的方法是使用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);
    

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

    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 &lt;= 3 不一定有效。将上述小提琴中的r 值与dense_rank 和rank 进行比较,您会发现不同之处。

    【讨论】:

      【解决方案2】:

      假设你有以下记录

      索引名称
      1 “ABC”
      2 “XYZ”
      2 “ABC”
      1 “XYZ”
      1“XYZ”

      在这种情况下,您可以区分选择不重复的记录。

      Select distinct index, name from table_name;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-27
        • 2016-05-01
        • 2017-08-08
        • 2015-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多