我有 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
,它将返回所有用户积分之和的MAX
和AVG
例如,我有:
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') )
在示例查询中,仅涉及 3 个结果。 它们是:
user_ID points activity_type_ID
1 1 8
3 2 8
3 1 8
我想得到:
- 用户 1 有 1 点
- 用户 3 有 3 点
- 最大值为 3,平均值为 2
相反,我得到的最大值是 2,平均值是 1.33
结果与您的查询一致,但您的查询不符合您的要求。
您的查询将计算相关记录中点的最大值和平均值。但是您似乎想要按用户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
这样做:
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