如果百分比高于某个值,则连接表



我的问题与此类似:比较行并获得百分比

然而,没有什么不同。我把我的问题改成了另一篇文章。

我有两张桌子。

第一张表:

user_id | post_id
1         1
1         2
1         3
2         12
2         15

第二表:

post_id | rating
1         1
1         2
1         3 
2         1
2         5
3         1
3         1
3         4
12        4
15        1

因此,现在我想在第二张表中计算每个帖子的评分。如果评级超过,比方说,50%的正面评级,我想得到post_id,并将其从表1中转到post_id中,并将1添加到user_id中。

最后,它将返回user_id和阳性帖子的数量。

上表的结果是:

user_id | helpfulPosts
1         2
2         1

post_id为1和3的帖子具有正面评价,因为超过50%的帖子具有1-3的评价。id=2的帖子不是正面的,因为评分正好是50%。

我将如何实现这一点?

澄清:这是一个mysql-rdbm和一个积极的帖子,其中带有1、2和3的rating_id的数量超过了总评分的一半。基本上是一样的,来自我上面发布的另一个帖子。

忘了一件事:还有一种可能性是posts表中存在一个post_id,但ratings_table中没有对其进行评级。这些帖子也很有帮助。以null作为评级的案例,对我来说是一个误解。

试试这个解决方案:

SELECT
    a.user_id,
    COUNT(1) AS helpfulPosts
FROM
    posts a
LEFT JOIN
    (
        SELECT 
            post_id, 
            COUNT(CASE WHEN rating IN (1,2,3) OR rating IS NULL THEN 1 END) / COUNT(1) AS percent_positive
        FROM ratings
        GROUP BY post_id
    ) b ON a.post_id = b.post_id
WHERE
    b.post_id IS NULL OR
    b.percent_positive > 0.5
GROUP BY
    a.user_id

SQL Fiddle演示

^请注意,我向user_id 1添加了没有评级的帖子,这些帖子将计入用户的helpfulPosts

select up.user_id, count(up.post_id) as helpfulPosts
from userposts as up
where up.post_id in (
    select pr.post_id
    from postratings as pr
    group by pr.post_id
    having
        sum(case when pr.rating between 4 and 5 then 0 else 1 end) > 
        sum(case when pr.rating between 4 and 5 then 1 else 0 end)
)
group by up.user_id

要解决这个问题,您需要首先弄清楚哪些帖子是有用的。根据你的逻辑,这只是计算一个评级存在时的平均评级。

select u.user_id, count(*) as HelpfulPosts
from UserPosts u join
     (select post_id,
             sum(case when rating in (1, 2, 3) then 1.0 else 0.0 end) / count(rating) as HelpfulRating 
      from PostRating pr
      group by post_id
     ) r
     on r.post_id = u.post_id
where r.HelpfulRating > 0.5
group by user_id

下一步是将其连接回用户帖子表,按用户id分组,以计算有用帖子的数量。

顺便说一句,我不认为"3"有什么帮助。你是说15吗?以上查询忽略NULL评级。如果NULL被认为是有用的,那么使用:

             sum(case when coalesce(rating, 1) in (1, 2, 3) then 1.0 else 0.0 end) / count(*) as HelpfulRating 

而不是查询中的版本。

最新更新