PSQL dense_rank 不同总项目中的一项

PSQL dense_rank of one item out of distinct total items

我可以使用以下 PSQL 查询(最后)在我的 table 中获取单行的 dense_rank,但是,我希望能够显示这是:

dense_rank OUT OF total distinct ranks

例如,由于 dense_rank 允许 'ties',可以这么说,如果我有 100 行并且所选行排名第 14(并且只有 59 个不同的排名),我会喜欢说:

Ranked 14th out of 59

有什么方法可以修改我的查询以实现此目的,还是我必须使用多个查询?

这是我的查询:

SELECT ranked.*
FROM
  (SELECT id,
          postable_id,
          spread_count,
          bury_count,
          read_count,
          (spread_count*3) + (bury_count*-2) + (read_count*-1) AS score,
          dense_rank() OVER (
                             ORDER BY (spread_count*3) + (bury_count*-2) + (read_count*-1) DESC) AS RANK
   FROM posts) AS ranked
WHERE id = ?

你可以试试这个。

SELECT t.*
FROM (SELECT ranked.*, 
      RNK||' out of '||MAX(RNK) OVER() as rnk_pos
      FROM
       (SELECT id,
          postable_id,
          spread_count,
          bury_count,
          read_count,
          (spread_count*3) + (bury_count*-2) + (read_count*-1) AS score,
          dense_rank() OVER (
                             ORDER BY (spread_count*3) + (bury_count*-2) + (read_count*-1) DESC) AS RNK
        FROM posts) AS ranked
      ) t
WHERE id=?

基本上,你想要这个:

SELECT p.*
FROM (SELECT p.*
             (spread_count*3) + (bury_count*-2) + (read_count*-1) AS score,
             dense_rank() OVER (ORDER BY (spread_count*3) + (bury_count*-2) + (read_count*-1) DESC) AS RANK,
             count(distinct (spread_count*3) + (bury_count*-2) + (read_count*-1)) over () as outof
      FROM posts p
     ) p
WHERE id = ?;

唉,这行不通,因为 Postgres 不支持 COUNT(DISTINCT) 作为 window 函数。您可以使用其他 window 函数来实现它:\

SELECT p.*
FROM (SELECT p.*,
             dense_rank() over (order by score desc) AS RANK,
             sum( (seqnum = 1)::int) as outof
      FROM (SELECT p.*,
                   (spread_count*3) + (bury_count*-2) + (read_count*-1) AS score,
                   row_number() over (partition by (spread_count*3) + (bury_count*-2) + (read_count*-1) AS score order by spread_scount) as seqnum
            FROM posts p
           ) p
     ) p
WHERE id = ?;