Mysql 如何在每个日期计算相同的组值

Mysql 如何在每个日期计算相同的组值,mysql,Mysql,我有这个 表2用户 id | name 1 john 2 smith 3 dalton 表2.订单 id | dates | user_id x 2017-01-01 1 x 2017-01-01 1 x 2017-01-01 2 x 2017-01-02 1 x 2017-01-02 3 x 2017-01-02 3 我希望这个结果使用纯mysql dates | john | smith | dalton 2017-01-01 | 2 | 1 | 0 2017-01-02 | 1 | 0

我有这个

表2用户

id | name
1 john
2 smith
3 dalton
表2.订单

id | dates | user_id
x 2017-01-01 1
x 2017-01-01 1
x 2017-01-01 2
x 2017-01-02 1
x 2017-01-02 3
x 2017-01-02 3
我希望这个结果使用纯mysql

dates | john | smith | dalton
2017-01-01 | 2 | 1 | 0
2017-01-02 | 1 | 0 | 2
我能做的只有这个
选择a.dates,b.name,count(*)作为表中的计数\u订单a左连接表\u用户b在a.user\u id=b.id组中按a.dates,b.name

结果:

dates | name | counts
2017-01-01 john 2
2017-01-01 smith 1
2017-01-02 john 1
2017-01-02 dalton 2
然后我使用php进行处理

那么,如何使用纯mysql实现这一点呢?
谢谢

您可以使用动态sql查询来完成

查询

set @query = null;
select
  group_concat(distinct
    concat(
      'coalesce(sum(case when `name` = ''',
      `name`, ''' then 1 end), 0) as `', `name` , '`'
    )
  ) into @query
from `your_table_name`;

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

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

您应该使用Pivot,但不要关闭此按钮。我现在尝试查看数据透视表。由于数据透视表无法正常工作,我将尝试编辑我的问题。棒极了,兄弟。thanks@plonknimbuzz当前位置如果它解决了你的问题,请将它标记为答案。我只是忙于探索你的代码XD.sry