2014-01-27 52 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