多列计数
Count of multiple columns
我在编写对 2 列中所有值的出现次数求和的查询时遇到问题。我有一个具有以下结构的 table:
+-----------+------------+
| player1ID | player2ID |
+-----------+------------+
| 1 | 2 |
| 1 | 3 |
| 2 | 3 |
| 1 | 4 |
+-----------+------------+
在 运行 查询之后,我想要这样的结果 table:
+-----------+------------+
| playerID | count |
+-----------+------------+
| 1 | 3 |
| 2 | 2 |
| 3 | 2 |
| 4 | 1 |
+-----------+------------+
我试过以下查询
select g1.player1ID, g1.count1 + g2.count2
from
(select player1ID, count(*) from table group by player1ID) as g1,
(select player2ID, count(*) from table group by player2ID) as g2
where player1ID = player2ID
但这只会在玩家出现在两列(player1ID 和 player2ID)中时给出计数,但如果它只出现在其中一列中则不会出现。
使用union all
合并两列。然后做聚合:
select playerID, count(*)
from ((select player1ID as playerID from table) union all
(select player2ID as playerID from table)
) t
group by playerID;
您可以像这样在派生的 table 中使用 union:
select player, count(*) as count
from (
select player1id player from table1
union all
select player2id player from table1
) sub
group by player;
我在编写对 2 列中所有值的出现次数求和的查询时遇到问题。我有一个具有以下结构的 table:
+-----------+------------+
| player1ID | player2ID |
+-----------+------------+
| 1 | 2 |
| 1 | 3 |
| 2 | 3 |
| 1 | 4 |
+-----------+------------+
在 运行 查询之后,我想要这样的结果 table:
+-----------+------------+
| playerID | count |
+-----------+------------+
| 1 | 3 |
| 2 | 2 |
| 3 | 2 |
| 4 | 1 |
+-----------+------------+
我试过以下查询
select g1.player1ID, g1.count1 + g2.count2
from
(select player1ID, count(*) from table group by player1ID) as g1,
(select player2ID, count(*) from table group by player2ID) as g2
where player1ID = player2ID
但这只会在玩家出现在两列(player1ID 和 player2ID)中时给出计数,但如果它只出现在其中一列中则不会出现。
使用union all
合并两列。然后做聚合:
select playerID, count(*)
from ((select player1ID as playerID from table) union all
(select player2ID as playerID from table)
) t
group by playerID;
您可以像这样在派生的 table 中使用 union:
select player, count(*) as count
from (
select player1id player from table1
union all
select player2id player from table1
) sub
group by player;