MySQL Count有几个标准列一个表

时间:2013-09-18 15:47:34

标签: mysql sql

我有一个数据交易表

Table Data (Month,Year,Type,Color)
+-------+------+-----------------------+---------------+
| Month | Year | type                  | Color         |
+-------+------+-----------------------+---------------+
|     1 | 2013 | MATIC                 | BLACK         |
|     1 | 2013 | MATIC                 | BLACK         |
|     2 | 2013 | MATIC                 | BLACK         |
|     2 | 2013 | MATIC                 | RED           |
|     3 | 2013 | MATIC                 | WHITE         |
|     3 | 2013 | MATIC                 | WHITE         |
|     4 | 2013 | MATIC                 | WHITE         |
|     4 | 2013 | MATIC                 | WHITE         |
|     1 | 2013 | SPORT                 | RED           |
|     1 | 2013 | SPORT                 | YELLOW        |
|     2 | 2013 | SPORT                 | YELLOW        |
|     2 | 2013 | SPORT                 | BLACK         |
|     3 | 2013 | SPORT                 | BLACK         |
+-------+------+-----------------------+---------------+

我想按类型,颜色,年份,月份计算数量 所以像这样的结果

+-------+------+-----------------------+---------------+--------+
| Month | Year | type                  | Color         | Number |
+-------+------+-----------------------+---------------+--------+
|     1 | 2013 | MATIC                 | BLACK         |      2 |
|     2 | 2013 | MATIC                 | BLACK         |      1 |
|     2 | 2013 | MATIC                 | RED           |      1 |
|     3 | 2013 | MATIC                 | WHITE         |      2 |
|     4 | 2013 | MATIC                 | WHITE         |      2 |
|     1 | 2013 | SPORT                 | RED           |      1 |
|     1 | 2013 | SPORT                 | YELLOW        |      1 |
|     2 | 2013 | SPORT                 | YELLOW        |      1 |
|     2 | 2013 | SPORT                 | BLACK         |      1 |
|     3 | 2013 | SPORT                 | BLACK         |      1 |
+-------+------+-----------------------+---------------+--------+

按月,年,类型,颜色分组 获取数字的查询是什么?

1 个答案:

答案 0 :(得分:3)

SELECT *, COUNT(*)
FROM table_name
GROUP BY month, year, type, color;  --  TA DA!