因此,我正在尝试构建一个查询,该查询将向我显示每种类型的活动,哪些用户拥有最多积分。你可以看到下面的表格结构。每个活动都有一个 activity_typeid ,每个活动都有一个 activity_weight 。
在下面的例子中,Bob的通话得分为50分,会议得分为100分。詹姆斯的得分为100分,会议得分为100分。
userid activity_typeid activity_weight
------------------------------------------------------------
123 (Bob) 8765 (calls) 50
123 (Bob) 8121 (meetings) 100
431 (James) 8765 (calls) 50
431 (James) 8121 (meetings) 100
431 (James) 8765 (calls) 50
我希望能够输出以下内容:
我事先没有知道 activity_typeid的,因为它们是随机输入的,所以我想知道是否可以构建某种计算的查询每个DISTINCT / UNIQUE activity_typeid 的SUM?
提前非常感谢。
答案 0 :(得分:2)
您需要的是等同于分析函数DENSE_RANK()
。如果您需要为每项活动做出最佳表现,那么可以采取一种方法
SELECT a.activity_typeid, GROUP_CONCAT(a.userid) userid
FROM
(
SELECT activity_typeid, userid, SUM(activity_weight) activity_weight
FROM table1
-- WHERE ...
GROUP BY userid, activity_typeid
) a JOIN
(
SELECT activity_typeid, MAX(activity_weight) activity_weight
FROM
(
SELECT activity_typeid, userid, SUM(activity_weight) activity_weight
FROM table1
-- WHERE ...
GROUP BY userid, activity_typeid
) q
GROUP BY activity_typeid
) b
ON a.activity_typeid = b.activity_typeid
AND a.activity_weight = b.activity_weight
GROUP BY activity_typeid
在MySQL中模拟DENSE_RANK()
的另一种方法是利用会话变量
SELECT activity_typeid, GROUP_CONCAT(userid) userid
FROM
(
SELECT activity_typeid, userid, activity_weight,
@n := IF(@g = activity_typeid, IF(@v = activity_weight, @n, @n + 1) , 1) rank,
@g := activity_typeid, @v := activity_weight
FROM
(
SELECT activity_typeid, userid,
SUM(activity_weight) activity_weight
FROM table1
-- WHERE ...
GROUP BY activity_typeid, userid
) q CROSS JOIN (SELECT @n := 0, @g := NULL, @v := NULL) i
ORDER BY activity_typeid, activity_weight DESC, userid
) q
WHERE rank = 1
GROUP BY activity_typeid
输出:
| ACTIVITY_TYPEID | USERID | |-----------------|---------| | 8121 | 123,431 | | 8765 | 431 |
以下是两个查询的 SQLFiddle 演示
答案 1 :(得分:0)
您必须使用GROUP BY
语句计算每个用户和每个活动typeid的总和。尝试这样的事情:
SELECT userid, activity_typeid, SUM(activity_weight)
FROM table
GROUP BY userid, activity_typeid
然后使用它作为子查询来确定每个activity_typeid的最佳执行者。
答案 2 :(得分:0)
如果您想使用聚合函数,则需要使用GROUP BY
,而不是DISTINCT
。您可以按userid
和activity_typeid
进行分组,然后选择SUM(activity_weight)
。
答案 3 :(得分:0)
当然,只需像这样使用group:
SELECT t.userid, t.activity_typeid, sum(t.activity_weight)
FROM YOURTABLE t
GROUP BY t.userid, t.activity_typeid
答案 4 :(得分:0)
查询以选择给定活动的(单个)最佳表现者:
SELECT userid, activity_typeid, SUM(activity_weight)
FROM ?
WHERE activity_typeid = ?
GROUP BY userid
ORDER BY SUM(activity_weight) DESC
LIMIT 1
您可以更改LIMIT
以输出前5或10位表演者,然后在代码中检查它们以查看您要显示的内容(例如,如果两个人的分数相同)。