【发布时间】:2021-06-29 12:10:54
【问题描述】:
我有一张包含游戏结果的表格。两列用于玩家姓名。玩家的名字可以出现在这两列中。在计算某个特定玩家的决斗频率时,我得到了错误的决斗计数。这是一个简化的描述,以保持对问题的关注。
这是我的表结果到目前为止发生的决斗:
| player1 | player2 |
|---|---|
| Alice | Bob |
| Christine | Daniel |
| Daniel | Christine |
| Christine | Daniel |
| Esme | Franz |
| Esme | Daniel |
| Garrey | Hans |
| Hans | Garrey |
我想得到的是,同一个名字出现在两列中的频率。请注意,Garrey 和 Hans 的决斗次数正确为 2:
| player | duels |
|---|---|
| Daniel | 4 |
| Christine | 3 |
| Esme | 2 |
| Garrey | 2 |
| Hans | 2 |
| Franz | 1 |
| Alice | 1 |
| Bob | 1 |
我的真实表和 SQL 语句计算其他统计数据更复杂,所以我需要两个 SELECT 结合一个 UNION,就像我在这个例子中使用的一样:
SELECT
playerName AS playerName,
SUM(duels) AS duels
FROM (
SELECT player1 AS playerName,
COUNT(player1) AS duels
FROM results
GROUP BY player1
UNION
SELECT player2 AS playerName,
COUNT(player2) AS duels
FROM results
GROUP BY player2
) AS A
GROUP BY playerName
ORDER BY duels DESC
现在的问题是,我弄错了 Garrey 和 Hans 的决斗次数 - 1 而不是 2:
| player | duels |
|---|---|
| Garrey | 1 |
| Hans | 1 |
如果我将 Garrey 和 Hans 的更多结果添加到我的表中,那么我的 SQL 语句将正确返回 3 的决斗计数。
这是fiddle。
我在这里做错了什么?据我了解,我试图在第一列中计算名称,然后在第二列中,然后将两个计数相加。我按照here 的建议尝试了另一种方法,使用 Count(*),但这导致所有结果都错误。
如有任何反馈,非常感谢!
【问题讨论】: