PostgreSQL - select 来自连接 table 的聚合列并用它来求和

PostgreSQL - select aggregated column from joined table and use it to sum

我想要 select 从三个 table 聚合的字段并输出 post、postIdcalculatedRate 和 [= 的三个字段15=],我试过但没用

目前我有这个示例查询只得到 countpostId

select
    mr.count,
    mr.postId
from
    (
        select
            "m"."postId" as postId,
            count("m"."postId") as count
        from
            "Rating" r
        left join "Messenger" m on
            "r"."id" = "m"."ratingId"
        group by
            "m"."postId"
    ) mr
group by
    mr.postId,
    mr.count

Messenger(映射 table 用于 Post 和评级)

id postId ratingId
1 1 4
2 1 5
3 2 6

Post

id title
1 post one
2 post two

评分

id a b
4 5.0 5.0
5 3.0 3.0
6 2.0 4.0

预期结果(calculatedRate = 同一 post id 内的平均值((rating.a + rating.b)/ 2))

id postId calculatedRate count
1 1 4.0 2
2 2 3.0 1

我不确定我得到了你要找的东西,但如果你想要每个 MESSENGER.IDCOUNTCALCULATEDRATE 那么下面应该做的

SELECT 
MESSENGER.ID,
POST.ID POSTID, 
COUNT(*) NR_RATINGS,
(RATING.A + RATING.B)/2 CALCULATEDRATE
FROM 
RATING JOIN MESSENGER ON RATING.ID = MESSENGER.RATINGID
JOIN POST ON MESSENGER.POSTID=POST.ID

编辑:如果您想要 post 的平均值,您可以通过以下

实现
SELECT 
POST.ID POSTID, 
COUNT(*) NR_RATINGS,
avg((RATING.A + RATING.B)/2) CALCULATEDRATE
FROM 
RATING JOIN MESSENGER ON RATING.ID = MESSENGER.RATINGID
JOIN POST ON MESSENGER.POSTID=POST.ID
GROUP BY POST.ID