how to get SUM from two different tables that are linked to third one

后端 未结 6 1360
故里飘歌
故里飘歌 2021-01-24 02:41

ok the problem is that I have to sum two sums from two tables that are linked

first table points:

id | user_id | point | hit
1  | 1       |     4 | yes
2         


        
相关标签:
6条回答
  • 2021-01-24 02:55

    Try formatting your bb field like this:

    SUM(p.point + e.earning)
    
    0 讨论(0)
  • 2021-01-24 02:55

    Small modification to ur code...assuming the id in both fields are not relevant...and ur trying to select user_id and not id

    SELECT p.user_id, SUM(p.point) + SUM(e.earning) AS bb 
    FROM points p JOIN earnings e ON p.user_id = e.user_id 
    WHERE (p.hit = "yes" OR p.hit = "no") 
    GROUP BY p.user_id
    
    0 讨论(0)
  • 2021-01-24 02:56

    If you want total earnings per user, you should probably start by identifying which users you want earnings for. The most sensible option is probably to use the users table itself as the basis.

    SELECT user_id,
           (SELECT SUM(point)
              FROM points
             WHERE user_id = u.user_id
           )
           +
           (SELECT SUM(earning)
              FROM earnings
             WHERE user_id = u.user_id
               AND p.hit IN ('yes', 'no')
           ) AS bb
      FROM users
    

    This approach has the added benefit of reporting on users who had no points and/or earnings.

    0 讨论(0)
  • 2021-01-24 03:07

    maybe something like:

    select goals.user_id, sum(goal) as goal from
    (select
      user_id, point as goal from points p where  (p.hit = "yes" OR p.hit = "no") 
    union all
    select
      user_id, earning as goal from earnings) goals
    group by goals.user_id
    
    0 讨论(0)
  • 2021-01-24 03:12

    The problem of you query is that with the join on the user field, you will get multiple rows... You have to do the sums and then put the data together, unless you have a 1-1 relationship between points and earnings tables (like the id)

    A solution could be to create the table with the two sums and join them to get your data

    select COALESCE(P.user_id, E.user_id), points, earnings, 
    

    sum(COALESCE(points,0) + COALESCE(earnings,0)) from

    (select user_id, sum(point) as points from points 
    

    where (p.hit = "yes" OR p.hit = "no") group by user_id) as P

    full outer join
    
    (select user_id, sum(earning) as earnings from earnings group by user_id) as E
    on P.user_id = E.user_id
    
    group by COALESCE(P.user_id, E.user_id)
    

    I used FULL OUTER JOIN and coalesce to be sure that data are provided eve if one of the table is missing. If this is not necessary, you could alter your join condition (to a LEFT OUTER JOIN if, for example, you need data only whenere there is at least one valid point)

    0 讨论(0)
  • 2021-01-24 03:12

    Try changing this

    SUM( SUM(p.point) + SUM(e.earning) )
    

    to

    SUM(p.point) + SUM(e.earning)
    
    0 讨论(0)
提交回复
热议问题