【问题标题】:PostgreSQL ranking and relatedPostgreSQL排名及相关
【发布时间】:2014-01-23 10:58:53
【问题描述】:

我有一个表格,其中存储了不同类别的用户 ID 及其分数。用户数量将不断变化。这些点也会不断变化(就像 stackoverflow 中的点)。因此,登录的用户将看到一个仪表板,其中显示了 3 个类别中的每一个 - 你有 850 分,前面有 950 个用户。这是我现在的查询 -

WITH USERS AS (
   SELECT COUNT(*) TOT 
   FROM user_pointS
) 
SELECT ' You have ' || points_cat1 ||' points and there are '|| tot-rnk || ' ahead of you '   
FROM (
    SELECT ID,  
           points_cat1, 
           rank() OVER (ORDER BY  points_cat1 DESC ) AS RNK 
    FROM user_pointS
  ) AS RANKED, 
    USERS
WHERE ID = 10

有没有更好的方法(性能方面)?我将不得不为 3 列重复此操作?

【问题讨论】:

    标签: sql performance postgresql ranking


    【解决方案1】:

    好吧,你可以在没有 CTE 的情况下做到这一点:

    SELECT ' You have ' || points_cat1 ||' points and there are '|| tot-rnk || ' ahead of you '   
    FROM (SELECT ID, points_cat1, 
                  rank() OVER (ORDER BY points_cat1 DESC ) AS RNK ,
                  count(*) over () as TOT
          FROM user_pointS
         ) RANKED
    WHERE ID = 10;
    

    您可以同时为所有三个类别执行此操作:

    SELECT ' You have ' || points_cat1 ||' points and there are '|| tot-rnk1 || ' ahead of you ',
           ' You have ' || points_cat2 ||' points and there are '|| tot-rnk2 || ' ahead of you ',
           ' You have ' || points_cat3 ||' points and there are '|| tot-rnk3 || ' ahead of you '
    
    FROM (SELECT ID, points_cat1, points_cat2, points_cat3,
                  rank() OVER (ORDER BY points_cat1 DESC ) AS RNK ,
                  rank() OVER (ORDER BY points_cat2 DESC ) AS RNK1 ,
                  rank() OVER (ORDER BY points_cat3 DESC ) AS RNK2 ,
                  count(*) over () as TOT
          FROM user_pointS
         ) RANKED
    WHERE ID = 10;
    

    您可能可以将tot-rnk 替换为反向排名:

     rank() OVER (ORDER BY points_cat1 ASC ) AS RNK
    

    但您需要对其进行测试以确保它可以为您提供预期的结果。

    【讨论】:

    • 外部选择中的points_cat1,2,3应该是rnk,rnk1,rnk2。除此之外,这有效。谢谢。
    • @Jayadevan 。 . .文字说你有这么多积分与排名无关。第二部分使用rnk 变量。但是,这是您的查询,因此您可以输入您想要的内容。
    • 当我使用您发布的查询时,我收到 ERROR: column "points_cat2" does not exist ,因为我们在内部 SELECT 中没有该列。所以我应该将这些列也添加到内部选择中。
    • @Jayadevan 。 . .我什至没有考虑查询的那部分。那只是因为子查询没有从原始表中选择这些列。查看我刚刚所做的更改。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 2021-10-01
    • 2012-11-04
    • 1970-01-01
    相关资源
    最近更新 更多