我有一个数据库,用于在CS:GO中存储玩家击杀次数,我正在尝试编写一个查询,以显示每个玩家的KD。
我编写了一个查询,该查询将使用别名显示每个玩家的杀戮和死亡。
SELECT
`Name`,
`SteamID` as PlayerID,
count(`EventType`) as kills,
(SELECT count(`EventType`)
FROM `logdata`
WHERE (`EventVariable` = PlayerID AND `EventType` = 'killed')
GROUP BY `EventVariable`
ORDER BY `count(``EventType``)` DESC) as deaths
FROM `logdata`
WHERE `EventType` = 'killed'
GROUP BY `EventType`, `Name`
ORDER BY kills DESC
要计算KD,我只需要将kills / deaths
分开即可,但是您不能使用别名来做到这一点,我读到我应该能够包装别名,例如(SELECT kills) / (SELECT deaths) as KD
,但是不起作用。
我目前正在使用查询结果在PHP中开发KD,但这并不是一个很好的方法。 (例如,我无法查询谁的KD最高)
所以,我的问题是,如果我无法使用别名进行计算,该如何计算KD?
答案 0 :(得分:1)
我可能只是使用两个完全独立的子查询来编写您的查询,这些子查询会计算出死亡人数:
SELECT
n.Name,
COALESCE(t1.kill_cnt, 0) AS kills,
COALESCE(t2.death_cnt, 0) AS deaths,
CASE WHEN t2.death_cnt > 0
THEN CAST(t1.kill_cnt / t2.death_cnt AS CHAR(50))
ELSE 'NA' END AS ratio
FROM
( SELECT DISTINCT Name FROM logdata ) n
LEFT JOIN
(
SELECT Name, COUNT(*) AS kill_cnt
FROM logdata
WHERE EventType = 'killed'
GROUP BY Name
) t1
ON
n.Name = t1.Name
LEFT JOIN
(
SELECT EventVariable AS Name, COUNT(*) AS death_cnt
FROM logdata
WHERE EventType = 'killed'
GROUP BY Name
) t2
ON
n.Name = t2.Name
请注意,我在上面使用别名为n
的子查询仅用于生成数据库中所有用户的完整列表。理想情况下,某处应该有一个专用的用户表。如果没有,并且您不喜欢我的方法,那么您将不得不想出其他方法来获取所有用户的列表。
答案 1 :(得分:0)
感谢蒂姆向我指出正确的方向并提出了疑问。我进行了一些更改以获取所需的结果,并希望发布最终结果。
SELECT
n.SteamID,
COALESCE(t1.kill_cnt, 0) AS kills,
COALESCE(t2.death_cnt, 0) AS deaths,
CASE WHEN t2.death_cnt > 0 THEN CAST(t1.kill_cnt / t2.death_cnt AS CHAR(50))
WHEN t1.kill_cnt = 0 THEN '0'
ELSE 'Infinite' END AS ratio
FROM
( SELECT DISTINCT SteamID FROM logdata ) n
LEFT JOIN
(
SELECT SteamID, COUNT(*) AS kill_cnt
FROM logdata
WHERE EventType = 'killed'
GROUP BY SteamID
) t1
ON
n.SteamID = t1.SteamID
LEFT JOIN
(
SELECT EventVariable AS SteamID, COUNT(*) AS death_cnt
FROM logdata
WHERE EventType = 'killed'
GROUP BY EventVariable
) t2
ON
n.SteamID = t2.SteamID
WHERE t1.kill_cnt > 0 or t2.death_cnt > 0
ORDER BY `ratio` DESC
我试图让KD 0像这样显示,但这并不是一天结束时那么重要,NULL很容易使用。