[英]How do I perform the following SQL sum?
假設我們有下表
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
我目前無法測試,但可以嘗試以下操作:
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
。
你可以試試看
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
知道分數是贊成還是反對的唯一方法是比較分數。
我將使用子查詢來首先確定點,然后對每個用戶進行總結:(假設您的表名是“點”):
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.