PSQL dense_rank中不同总项目中的一项

时间:2017-05-30 21:12:38

标签: sql postgresql window-functions dense-rank

我能够使用以下PSQL查询(最后)来获取表格中单行的dense_rank,但是,我希望能够将其显示为:< / p>

dense_rank OUT OF total distinct ranks

例如,由于dense_rank允许“联系”,可以这么说,如果我有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 = ?

2 个答案:

答案 0 :(得分:1)

你可以试试这个。

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=?

答案 1 :(得分:0)

基本上,你想要这个:

\r\n

唉,这不起作用,因为Postgres不支持 Dim rs As New ADODB.Recordset Dim strSQL As String strSQL = "DELETE FROM mytable WHERE mycol>5;" ConnectDB rs.Open strSQL, ConnDB 作为窗口函数。您可以使用其他窗口函数实现它:\

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 = ?;