postgresql |合并查询结果

jmo0nnb3  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(264)

我有一个“简单”的情况,但我不能解决它自己。所以我需要的是将第一个查询的一个结果与第二个查询的结果组合起来,得到一个“最终结果”。
第一个查询获取玩家的射击次数。

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

第二个是获得点击率。

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

我需要的是计算准确度(命中/放炮*100),显示类似的结果。

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

8yoxcaq71#

你可以用 join 聚合后:

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

你真的打算 COUNT() ? 看来 SUM() 更合适。
而且,这只返回两个表中的玩家。如果你想让玩家在任何一个表中,使用 FULL JOIN .

相关问题