Search code examples
mysqlcountsubtraction

MySQL calculate difference in count column between two queries


I have two different queries. One for "plus" and one for "minus". I want to find the difference in the count value for each player.

I tried union all and got some very weird numbers.

Here are the results of each query which I ned to find the difference of:

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

How would I accomplish this? Thanks in advance for your help. I am a noob...

UGH...Trying to do the join method. Having issues, getting no results, just 4 empty columns. This is what I am trying

SELECT
  *
FROM
  (
    SELECT
        statement for plus results here
  ) AS tp
  JOIN (
    SELECT
        statement for minus results here
  ) AS tm ON tp.fk_plus_player1_id = tm.fk_minus_player1_id
GROUP BY
    fk_plus_player1_id

suggestions??


Solution

  • You have two tables. You want for each player, the difference of the counts.

    So :

    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;
    

    Maybe this is what you're looking for ?

    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))