在我们使用数据库的时候,可能会遇到需要进行统计的情况。

比如需要统计一下,下表中各个年份的胜负场数。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

MySQL中group by , sum , case when then 的使用 随笔 第1张

MySQL中group by , sum , case when then 的使用 随笔 第2张

遇到这样的情况,我们应该怎么办呢?

在mysql中我们可以使用group by sum  case when 来解决这个问题,sql语句如下:

select date_year,
sum(case when win_lose = '胜' then 1 else 0 end) win,
sum(case when win_lose = '负' then 1 else 0 end) lose
from scores group by date_year;

结果如下:

+-----------+------+------+
| date_year | win | lose |
+-----------+------+------+
| 2005 | 1 | 1 |
| 2006 | 2 | 1 |
| 2007 | 0 | 1 |
| 2008 | 2 | 1 |
| 2009 | 0 | 2 |
| 2010 | 1 | 1 |
| 2011 | 2 | 0 |
| 2012 | 2 | 1 |
| 2013 | 1 | 1 |
| 2014 | 3 | 2 |
| 2015 | 2 | 2 |
| 2016 | 1 | 0 |
| 2017 | 1 | 1 |
| 2018 | 1 | 3 |
+-----------+------+------+
14 rows in set (0.00 sec)

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄