将查询的一个结果除以另一个的结果

时间:2012-11-29 08:28:09

标签: mysql sql

我可以跑

SELECT killedby, COUNT(killedby) killcount FROM games_playerinfo WHERE killedby != '' GROUP BY killedby

ond get

killedby    killcount
Player1         1
Player2         1

我可以跑

SELECT ign, COUNT(ign) numberofgames FROM games_playerinfo GROUP by ign

并获取

ign numberofgames
player1 7
player2 3
player3 3
player4 3

我想将第一个查询的每个结果除以第一个查询中每个用户的第二个查询的结果。

所以结果应该是

ign      avgkillcount
player1  0.1429
player2  0.333333

我想在一个查询中执行此操作,以便限制结果。 我已经尝试过使用INNER JOINS,但我认为我不太了解连接,甚至不知道它是否可以达到我想要的目的。

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT
  t1.ign,
  (t1.numberofgames / t2.killcount) AS avgkillcount
FROM
(
    SELECT 
      ign, 
      COUNT(ign) numberofgames 
    FROM games_playerinfo 
    GROUP by ign
) t1
INNER JOIN
(
    SELECT 
      killedby, 
      COUNT(killedby) killcount
    FROM games_playerinfo 
    WHERE killedby != ''
    GROUP BY killedby
) t2 ON t1.ign = t2.killedby;

SQL Fiddle Demo

答案 1 :(得分:1)

查询:

SELECT g1.killedby ign,
       COUNT(g1.killedby)/(SELECT COUNT(ign) numberofgames 
                                  FROM games_playerinfo 
                                  WHERE ign = g1.killedby
                                  GROUP by ign) avgkillcount
FROM games_playerinfo g1
WHERE g1.killedby != '' 
GROUP BY g1.killedby