2014-01-27 50 views
2

我在SQLLite数据库中有一个像这样的表。 Name1是玩家1的名字(与name2相同),winner代表哪个玩家获胜(例如第一排,JOE获胜)。计算多个值事件

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

Ex。为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) 

这是我迄今为止,但它只输出的所有球员的名字:

 
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 

回答

4

这里:

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

数据是一种聚合和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); 
+0

谢谢你,它的工作原理。我想赢得“JOE”,而不是对手,但你的代码很容易改变。 – domen