Mysql Group by Year和Count字段

时间:2013-12-23 06:57:51

标签: mysql sql

例如,我有一个这样的表:

|  id  |  name  |  register_date  |  gender  |

|1     |John    |2011-02-02       |man       |
|2     |Jane    |2011-02-02       |woman     |
|3     |Jihn    |2012-04-04       |man       |
|4     |Jeni    |2012-02-02       |woman     |
|5     |Joni    |2012-02-02       |woman     |

查询如何从上面的表创建此结果?

|  RegisterYear  |  man  |  woman  |

|2011            |   1   |    1    |
|2012            |   1   |    2    |

2 个答案:

答案 0 :(得分:3)

按年份分组并将每个性别相加

select year(register_date) as registeryear,
       sum(gender = 'man') as man,
       sum(gender = 'woman') as woman       
from your_table
group by registeryear

答案 1 :(得分:0)

你走了:

SELECT YEAR(register_date) as RegisterYear,
       SUM(gender = 'man') as man,
       SUM(gender = 'woman') as woman
from register 
group by RegisterYear;

SQLFiddle Demo

输出:

REGISTERYEAR    MAN     WOMAN
===================================
2011            1       1
2012            1       2