MySQL计数出现在两个列中

时间:2017-03-06 11:53:32

标签: mysql sql

我有ff。结构:

id|player1|player2|win   |lose  |leave|status
1 |151663 |150000 |151663|150000|0    |1
2 |150000 |151663 |150000|151663|0    |1
3 |151663 |150000 |151663|150000|0    |1

我需要像

这样的结果
player|win|lose|leave
150000|1  |2   |0
151663|2  |1   |0

谢谢! :)

2 个答案:

答案 0 :(得分:2)

您可以使用union all和聚合:

select player, sum(win) as wins, sum(lose) as losses,
       sum(leave) as leaves
from ((select win as player, 1 as win, 0 as lose, 0 as leave
       from ff
       where win <> 0
      ) union all
      (select lose as player, 0 as win, 1 as lose, 0 as leave
       from ff
       where lose <> 0
      ) union all
      (select leave as player, 0 as win, 0 as lose, 1 as leave
       from ff
       where leave <> 0
      )
     ) wll
group by player;

答案 1 :(得分:0)

SELECT Player,sum(win)win,sum(lose)lose,leave FROM(
SELECT win Player,1 as win,0 as lose,leave FROM @Table 
UNION ALL
SELECT lose Player,0 as win,1 as lose,leave FROM @Table
)A group by Player,leave