Max&两张桌子的AVG MYSQL INNER JOIN

时间:2017-05-08 19:43:47

标签: mysql inner-join

我有2张桌子(例子):

用户:

ID    company_ID
1     7
2     6
3     7

activity_rewards:

user_ID    points    activity_type_ID
1          1         7
1          2         7
1          1         7
1          1         8
2          1         7
2          1         7
2          2         8
2          1         7
3          2         7
3          1         7
3          2         8
3          1         8

(还有公司和activity_types表,但它们在这里不相关)

我需要一个MYSQL查询,它会将每个用户WHERE的所有用户的总点数加起来company_ID,某个activity_type_ID并且它将返回{{1} }和所有用户点之和的MAX

我有例如:

AVG

在示例查询中,仅涉及3个结果。他们是:

SELECT SUM(activity_rewards.points) AS totalpoints, 
  MAX(activity_rewards.points) AS maxpoints, 
  AVG(activity_rewards.points) AS avgpoints 
FROM activity_rewards
INNER JOIN users 
  ON activity_rewards.user_ID = users.ID 
WHERE ( (users.company_ID = "7") && (activity_rewards.activity_type_ID LIKE '8') )

我想得到:

  • 用户1有1分
  • 用户3有3分
  • Max是3平均值是2
相反,我得到Max是2,平均值是1.33

2 个答案:

答案 0 :(得分:2)

结果与您的查询一致,但您的查询不符合您的要求。

您的查询计算相关记录中点的最大值和平均值。但您似乎想要用户ID总和的最大值和平均值。

这意味着您需要计算子查询中每个用户的点数总和,然后计算外部查询中的最大值和平均值。

SELECT SUM(sumpoints) as totalpoints, max(sumpoints) as maxpoints, avg(sumpoints) as avgpoints
FROM
    (SELECT users.ID, SUM(activity_rewards.points) AS sumpoints
    FROM activity_rewards
    INNER JOIN users ON activity_rewards.user_ID = users.ID 
    WHERE users.company_ID = 7 and activity_rewards.activity_type_ID = 8
    GROUP BY users.ID) t

答案 1 :(得分:0)

这样做:

SELECT MAX(sum_points) max, AVG(sum_points) avg, SUM(sum_points) sum_all FROM (SELECT SUM(t2.points) sum_points FROM users t1 JOIN activity_rewards t2 ON (t1.ID = t2.user_ID) WHERE ( (t1.company_ID = "7") AND (t2.activity_type_ID = '8') ) GROUP by t1.ID) as summation