mysql在select上查询多个组

时间:2017-03-03 05:04:11

标签: mysql select group-by

我有一张这样的表:

+------+-----------+-----------+-----------+
| id | company | ename | age | 
+------+-----------+-----------+-----------+
| 1 | c1 | fenice | 15 |
| 2 | c1 | wing | 16 | 
| 3 | c1 | destiny | 17 | 
| 4 | c1 | heavyarms | 15 |
| 5 | c2 | sazabi | 15 | 
| 6 | c2 | unicorn | 16 | 
| 7 | c2 | aegis | 16 | 
| 8 | c2 | strike | 15 |
| 9 | c3 | freedom | 17 |
| 15 | c3 | kshatriya | 17 |
| 16 | c3 | exia | 16 |
| 17 | c3 | barbatos | 15 |
+------+-----------+-----------+-----------+

我知道如何计算和分组但是 有什么方法可以在csv上生成这样的东西吗?

+-----+----+----+----+ 
| age | c1 | c2 | c3 | 
+-----+----+----+----+
|  15 |  2 |  2 |  1 | 
|  16 |  1 |  2 |  1 | 
|  17 |  1 |  0 |  2 | 
+-----+----+----+----+

2 个答案:

答案 0 :(得分:2)

创建动态sql查询并执行。

<强>查询

set @query = null;
select
  group_concat(distinct
    concat(
      'count(case when `company` = ''',
      `company`, ''' then `ename` end) as ',company
    )
  ) into @query
from `your_table_name`;

set @query = concat('select `age`, ', @query, ' from `your_table_name` 
                  group by `age`
');

prepare stmt from @query;
execute stmt;
deallocate prepare stmt;

<强>结果

+-----+----+----+----+
| age | c1 | c2 | c3 |
+-----+----+----+----+
|  15 |  2 |  2 |  1 |
|  16 |  1 |  2 |  1 |
|  17 |  1 |  0 |  2 |
+-----+----+----+----+

Sql Fiddle demo

答案 1 :(得分:0)

试试这个

select 
age,sum(field(company,'c1')) as c1,sum(field(company,'c2')) as c2,sum(field(company,'c3')) as c3 
from table_name group by age;