简体   繁体   English

MySQL 每个查询多次计数

[英]MySQL multiple counts per query

I have a table with 2 fields, status and datetime.我有一个包含 2 个字段、状态和日期时间的表。 I want to count each status type.我想计算每种状态类型。

My table:我的桌子:

datetime, status set(0,1,2,3)

my query:我的查询:

select date_format(mydate,'%d-%m') as days, count(*) as total, status from mytable where mydate >= date_sub(curdate(), interval 30 day) group by days, status ORDER BY days DESC

What my query returns:我的查询返回的内容:

07/05/2020 1234 0
07/05/2020 8277 1
07/05/2020 2343 2
07/05/2020 9827 3

What I want:我想要的是:

07/05/2020 1234 8277 2343 9827
06/05/2020 .... .... ... ...
05/05/2020 . . . .

If you have a predefined list of status es, you can do conditional aggregation:如果您有预定义的status列表,则可以进行条件聚合:

select
    date(mydate) days,
    sum(status = 0) status_O,
    sum(status = 1) status_1,
    sum(status = 2) status_2,
    sum(status = 3) status_3
from mytable
where mydate >= current_date - interval 30 day
group by days

Otherwise, you need dynamic SQL;否则需要动态SQL; that is, use a query to generate the actual query, then execute it.也就是说,使用查询生成实际查询,然后执行它。

For your use case, this should look like:对于您的用例,这应该如下所示:

set @sql = null;

select group_concat(
    distinct concat('sum(status = ', status, ') as status_', status)
    delimiter ', '
    order by status
) into @sql
from mytable;

set @sql = concat('select date(mydate) days, ', @sql, ' from mytable group by days');

prepare stmt from @sql;
execute stmt;
deallocate prepate stmt;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM