假设我们有下表
match_id, user_id, score
1000, 1, 359
1000, 52, 290
1001, 1, 429
1001, 59, 374
基本上在match_id 1000中,user_id 1获胜359-290,在match_id 1001中,user_id 1获胜429-374
计算总分数用户1很容易
select user_id,sum(score) as pointsfor group by user_id
如何确定得分数?基本上,以下SQL中的X应该是什么?
select user_id,sum(score) as pointsfor,sum(X) as pointsagainst group by user_id
答案 0 :(得分:2)
我现在无法测试,但尝试类似:
SELECT
PointsFor.user_id,
sum(PointsFor.score) as pointsfor,
sum(PointsAgainst.score) as pointsAgainst
FROM TABLE_NAME PointsFor
JOIN TABLE_NAME PointsAgainst
on PointsFor.match_id = PointsAgainst.match_id
and PointsFor.user_id <> PointsAgainst.user_id
GROUP BY PointsFor.user_id
视频:将上面的TABLE_NAME
替换为您桌子的实际名称。
答案 1 :(得分:1)
你可以尝试一下
select user_id, sum(score) as pointsfor,
(select sum(score)
from tab b
where a.match_id=b.match_id and a.user_id !=b.user_id) as pointsagainst
from tab a
group by user_id
答案 2 :(得分:0)
了解分数是赞成还是反对的唯一方法是比较分数。
我使用子查询首先确定点数,然后按用户总结:(这假定您的表名是“点”):
select user_id, SUM(pointsfor) as PointsFor, SUM(pointsagainst) as PointsAgainst, SUM(pointstied) as PointsTied
from (
select a.user_id, case when a.score > b.score then a.score else 0 end as PointsFor,
case when a.score < b.score then a.score else 0 end as PointsAgainst,
case when a.score = b.score then a.score else 0 end as PointsTied
from points a
join Points b on a.match_id = b.match_id and a.user_id != b.user_id
) sub
group by sub.user_id