如何在主查询中遍历CTE

时间:2019-07-22 16:16:27

标签: sql database postgresql

我正在尝试根据系统上的用户totalArticleViews和用户totalArticle对用户进行排名。排名应基于公式(totalArticleViews + ( totalArticles * 500 )) / 100

我有一个允许用户发布文章的系统,每当任何人阅读其中的任何文章时,都会创建一条记录。我的数据库具有下表。 usersarticlesreads

我试图将视图插入到公式中,但是在获取所有用户文章并将其乘以500以插入到公式中以对它们进行排名时遇到问题

with article_views AS (
 SELECT article_id, COUNT(reads.id) AS views, 1 * 500 AS points
 FROM reads 
 WHERE article_id IN (     
 SELECT id FROM articles WHERE articles.published_on IS NOT NULL AND 
  articles.deleted_at IS NULL
 ) 
GROUP BY article_id
),
published AS (
SELECT COUNT(articles.id) AS TotalArticle, COUNT(articles.id) * 500 AS 
points
FROM articles 
WHERE published_on IS NOT NULL AND deleted_at IS NULL
GROUP BY articles.user_id
)

SELECT 
 users.id AS user_id, 
 ROUND((SUM(article_views.views) + () ) / 100.0, 2)  AS points,
 ROW_NUMBER() OVER (ORDER BY ROUND((SUM(article_views.views) + ()) / 
100.0, 2) DESC)
FROM users 
 LEFT JOIN articles ON users.id = articles.user_id
 LEFT JOIN reads ON articles.id = reads.article_id
 LEFT JOIN article_views ON reads.article_id = article_views.article_id
WHERE 
 users.id IN (SELECT user_id FROM role_user WHERE role_id = 2)
 AND status = 'ACTIVE'
GROUP BY users.id
ORDER BY points DESC NULLS LAST

我现在被困住了

(SUM(article_views.views) + () ) / 100.0, 2)

1 个答案:

答案 0 :(得分:2)

只需通过在GROUP BY中包含SELECT user_id ,然后将 published 加入到 published CTE中,在主要查询中按此字段用户

WITH article_views AS (
    SELECT r.article_id, 
           COUNT(r.id) AS views, 
           1 * 500 AS points
    FROM reads r
    WHERE r.article_id IN (     
         SELECT id 
         FROM articles a 
         WHERE a.published_on IS NOT NULL
           AND a.deleted_at IS NULL
    ) 
    GROUP BY r.article_id
),
published AS (
   SELECT a.user_id,
          COUNT(a.id) AS TotalArticle, 
          COUNT(a.id) * 500 AS points
   FROM articles a
   WHERE a.published_on IS NOT NULL 
     AND a.deleted_at IS NULL
   GROUP BY a.user_id
)

SELECT u.id AS user_id, 
       ROUND((SUM(av.views) + (p.TotalArticle)) / 100.0, 2)  AS points,
       ROW_NUMBER() OVER (ORDER BY ROUND((SUM(av.views) + (p.TotalArticle)) 
                                          / 100.0, 2) DESC) AS rn
FROM users u
LEFT JOIN articles a ON u.id = a.user_id
LEFT JOIN reads r ON a.id = r.article_id
LEFT JOIN article_views av ON r.article_id = av.article_id
LEFT JOIN published p ON u.id = p.user_id
WHERE u.id IN (
     SELECT user_id FROM role_user WHERE role_id = 2
)
AND u.status = 'ACTIVE'
GROUP BY u.id
ORDER BY points DESC NULLS LAST
相关问题