Search code examples
sqlpostgresqljoinaggregation

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


I want to select fields that aggregated from three tables and output three fields for the post, postId, calculatedRate and count, i tried but not working

currently i have this sample query just get count and 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 (mapping table for Post and Rating)

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

Post

id title
1 post one
2 post two

Rating

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

Expected result (calculatedRate = average within same post id((rating.a + rating.b) / 2))

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

Solution

  • I'm not sure I got what you're looking for, but if you want the COUNT and CALCULATEDRATE for each MESSENGER.ID then the following should do it

    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
    

    Edit: if you want the average by post you can achieve that with the following

    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