2017-05-30 74 views
0

我可以使用以下PSQL查詢(最後)獲取我表格中單行的dense_rank,但是,我希望能夠顯示此爲:PSQL dense_rank中不同項目中的一個項目

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

回答

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

這似乎工作@vkp,謝謝!如果你有時間,你能解釋這個黑魔法嗎?非常感激。 – lightyrs

+1

@lightyrs ..我添加的唯一附加功能是獲得最高排名(即本例中爲59)的MAX(RNK)OVER()。 'RNK'就是你已經計算好的。連接它們會得到你所需要的。 –

0

基本上,你想這樣:

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)作爲窗口函數。您可以使用其他窗口功能實現它:\

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 = ?; 
相關問題