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

时间:2017-10-31 07:58:23

标签: mysql

我有这个

table_user

id | name
1 john
2 smith
3 dalton

table_order

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

我能做的只是这个 select a.dates, b.name, count(*) as counts from table_orders a left join table_user b on a.user_id=b.id group by 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做到这一点? 感谢

1 个答案:

答案 0 :(得分:1)

您可以使用动态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;

Find a demo here