1

I have a "simple" situation here, but I couldn't resolve it by myself. So what I need is combine one result from the first query with the second one, to get a "final result".

The first query get the number of shots by player.

SELECT player, COUNT(shot) shots FROM table1 GROUP BY player;
+---------+-------+
| player  | shots |
+---------+-------+
| player1 | 10    |
+---------+-------+
| player2 | 10    |
+---------+-------+

The second is to get the hits.

SELECT player, COUNT(hit) hits FROM table2 GROUP BY player;
+---------+-------+
| player  | hits  |
+---------+-------+
| player1 | 10    |
+---------+-------+
| player2 | 5     |
+---------+-------+

And what I need is to calculate the accuracy (hits / shots * 100), displaying the result something like that.

+---------+-------+------+-----+
| player  | shots | hits | acc |
+---------+-------+------+-----+
| player1 | 10    | 10   | 100 |
+---------+-------+------+-----+
| player2 | 10    | 5    | 50  |
+---------+-------+------+-----+

1 Answer 1

2

You can use join after aggregation:

SELECT player, s.shots, h.hits
FROM (SELECT player, COUNT(shot) as shots
      FROM table1
      GROUP BY player
     ) s JOIN
     (SELECT player, COUNT(hit) as hits
      FROM table2
      GROUP BY player
     ) h
     USING (player);

Do you really intend COUNT()? It seems that SUM() would be more appropriate.

Also, this only returns players in both tables. If you want players in either table, use FULL JOIN.

Sign up to request clarification or add additional context in comments.

1 Comment

Thx! This solution works for me. I have to use COUNT() because it's kind of log table, so each line counts as shot or hit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.