Stai chiedendo SQL dinamico. Cioè, crea dinamicamente la stringa di query da un'altra query che elenca event_type
distinti valori, quindi eseguirlo. In MySQL, questo viene implementato utilizzando istruzioni preparate.
Ecco come farlo:
select @sql := group_concat(distinct
'sum(case when event_type = ''',
event_type, ''' then number else 0 end)/sum(number) as `ratio_',
event_type, '`'
)
from example_table;
set @sql = concat(
'select date(created_at) date_bucket, ',
@sql,
' from example_table group by date(created_at) order by date_bucket'
);
-- debug
select @sql;
-- execute
prepare stmt from @sql;
execute stmt;
deallocate prepare stmt;
Per i tuoi dati di esempio, questo produce la seguente query:
select
date(created_at) date_bucket,
sum(case when event_type = 'exampleG1' then number else 0 end)/sum(number) as `ratio_exampleG1`,
sum(case when event_type = 'exampleG2' then number else 0 end)/sum(number) as `ratio_exampleG2`,
sum(case when event_type = 'exampleG3' then number else 0 end)/sum(number) as `ratio_exampleG3`
from example_table
group by date(created_at)
order by date_bucket
E il seguente risultato:
date_bucket | ratio_exampleG1 | ratio_exampleG2 | ratio_exampleG3 :---------- | --------------: | --------------: | --------------: 2020-06-02 | 0.1429 | 0.2857 | 0.5714 2020-06-03 | 1.0000 | 0.0000 | 0.0000