我有两个不同的查询。一个用于"加"和#34;减去"。我想找到每个玩家的计数值差异。
我尝试了所有联盟,得到了一些非常奇怪的数字。
以下是每个查询的结果,我发现它们的区别在于:
fk_plus_player1_id cnt
90 71
65 68
79 66
45 59
64 57
27 56
55 56
93 55
37 55
40 44
1 36
84 33
20 31
24 28
8 23
fk_minus_player1_id cnt
93 44
64 42
79 40
37 35
90 33
20 31
84 31
27 30
65 30
40 26
1 26
24 25
45 25
55 22
8 10
我将如何做到这一点?在此先感谢您的帮助。我是个菜鸟......
UGH ...尝试进行连接方法。有问题,没有结果,只有4个空列。这就是我想要的
SELECT * FROM(此处为plus结果的select语句)AS tp
JOIN
(在此选择减去结果的陈述)AS tm
ON tp.fk_plus_player1_id = tm.fk_minus_player1_id
GROUP BY fk_plus_player1_id
建议??
答案 0 :(得分:0)
你有两张桌子。 你想要每个球员,计数的差异。
所以:
SELECT t1.fk_minus_player1_id AS player, ABS(t1.cnt - t2.cnt) AS difference
FROM table1 t1, table2 t2
WHERE t1.fk_minus_player1_id = t2.fk_plus_player1_id
GROUP BY t1.fk_minus_player1_id;
也许这就是你要找的东西?
WITH query1 AS
(SELECT t1.fk_minus_player1_id AS player, (t1.cnt - IFNULL(t2.cnt,0)) AS difference
FROM table1 t1 LEFT OUTER JOIN table2 t2 ON t1.fk_minus_player1_id = t2.fk_plus_player1_id
GROUP BY t1.fk_minus_player1_id),
query2 AS (SELECT t2.fk_plus_player1_id AS player, (IFNULL(t1.cnt,0) - t2.cnt) AS difference
FROM table2 t2 LEFT OUTER JOIN table1 t1 ON t1.fk_minus_player1_id = t2.fk_plus_player1_id
GROUP BY t2.fk_plus_player1_id)
(SELECT player, difference
FROM query1)
UNION
(SELECT player, difference
FROM query2 WHERE player NOT IN (SELECT player FROM query1))
答案 1 :(得分:0)
您冒着两个名单中不存在相同玩家的风险。解决方案为union all
group by
:
select player1id, sum(pluscnt) as pluscnt, sum(minuscnt) as minuscnt,
(sum(pluscnt) - sum(minuscnt)) as diff
from ((select player1id, cnt as pluscnt, 0 as minuscnt
from plustable
) union all
(select player1id, 0, cnt
from minustable
)
) t
group by player1id;