简体   繁体   English

MySQL在两列中的出现次数

[英]MySQL count of occurrences in two columns

I have the ff. 我有事。 structure: 结构体:

+----+---------+---------+---------+---------+---------+--------+
| 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 |
+----+---------+---------+---------+---------+---------+--------+

How do I generate a query if I need a result like below? 如果需要以下结果,如何生成查询?

+--------+-----+------+-------+
| player | win | lose | leave |
+--------+-----+------+-------+
| 150000 |   1 |    2 |     0 |
| 151663 |   2 |    1 |     0 |
+--------+-----+------+-------+

You can use union all and aggregation: 您可以使用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;
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM