【发布时间】:2021-09-07 15:21:41
【问题描述】:
我想选择从三个表中聚合的字段,并为帖子输出三个字段,postId、calculatedRate 和 count,我试过但没有用
目前我有这个示例查询只得到count 和postId
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(帖子和评级的映射表)
| id | postId | ratingId |
|---|---|---|
| 1 | 1 | 4 |
| 2 | 1 | 5 |
| 3 | 2 | 6 |
发帖
| 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 = 同一帖子 id 内的平均值((rating.a + rating.b)/ 2))
| id | postId | calculatedRate | count |
|---|---|---|---|
| 1 | 1 | 4.0 | 2 |
| 2 | 2 | 3.0 | 1 |
【问题讨论】:
标签: sql postgresql join aggregation