MySQL - 按列分组数据

时间:2013-03-21 18:28:07

标签: mysql database

作为我的第一个post的后续工作,我要求帮助将数据操作到excel数据透视表中,我推测这只能通过使用联合的数据库命令来完成。因此,我提交了一个具有相同数据的新问题,但是从MySQL的角度来看。

我有下表:

mysql> select * from ilike;
+-----------+------------+----------+
| likebread | likecheese | likemilk |
+-----------+------------+----------+
| girl      | boy        | girl     |
| boy       | girl       | boy      |
| boy       | boy        | boy      |
| boy       | boy        | girl     |
| boy       | boy        | boy      |
| boy       | girl       | boy      |
| girl      | boy        | girl     |
| boy       | girl       | girl     |
| boy       | boy        | girl     |
| girl      | boy        | boy      |
+-----------+------------+----------+
10 rows in set (0.00 sec)

我想计算和分组各列中的数据,以便最终结果是一个表格,显示每个相应列的男孩和女孩的计数,如下所示:

        +-----------+------------+----------+
        | likebread | likecheese | likemilk |
+-------+-------+------------+--------------+
| boys  | 7         | 7          | 5        |
| girls | 3         | 3          | 5        |
+-------+-----------+------------+----------+

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

这是一种方式:

select g.gender,
       sum(case when likebread=g.gender then 1 end) likebread,
       sum(case when likecheese=g.gender then 1 end) likecheese,
       sum(case when likemilk=g.gender then 1 end) likemilk
from (select 'girl' gender union select 'boy') g
cross join ilike
group by g.gender

<强>结果

| GENDER | LIKEBREAD | LIKECHEESE | LIKEMILK |
----------------------------------------------
|    boy |         7 |          7 |        5 |
|   girl |         3 |          3 |        5 |

See the demo