计算多个值出现次数

时间:2014-01-27 17:15:13

标签: android sql database sqlite

我在SQLLite数据库中有这样的表。 Name1是玩家1的名称(name2相同),winner代表哪个玩家获胜(例如,第一行,JOE赢了)。

我想获得特定玩家的所有对手的名字,玩家赢得该玩家的胜利数量以及他们玩过多少次。

实施例。 JOE的输出:

name    wins    games
----------------------  
BILL    1       2     (JOE played againts BILL 2 times and JOE won 1)
NICK    2       2
GREG    1       3     (JOE played againts GREG 3 times and JOE won 1)

这是我到目前为止所做的,但它只输出所有玩家的名字:

SELECT name2 FROM games WHERE name1="JOE"
UNION
SELECT name11 FROM games WHERE name2="JOE"

games中的数据:

id  name1       name2     winner  
----------------------------------------
1   JOE          BILL       1
2   BILL         JOE        1
3   NICK         JOE        2
4   JOE          NICK       1
5   NICK         BILL       1
6   GREG         JOE        1
7   GREG         JOE        2
8   GREG         JOE        1

1 个答案:

答案 0 :(得分:4)

这是一种使用聚合和case语句的方法。计算每个游戏的获胜者有点棘手,因为获胜者指的是name1name2列。你似乎想要对手获胜,所以这个逻辑确保winner不是指JOE

select (case when name1 = 'JOE' then name2 else name1 end) as name,
       sum(case when name1 = 'JOE' and winner = 2 then 1
                when name2 = 'JOE' and winner = 1 then 1
                else 0
           end) as wins,
       count(*) as games
from games g
where 'JOE' in (name1, name2)
group by (case when name1 = 'JOE' then name2 else name1 end);