如何计算 MySQL 中最近 10 天和两个不同集合的值
How to count values in MySQL for last 10 days and two different sets
我有一个 Laravel 仪表板,它根据两个不同的状态 activity 从该用户填充过去 10 天的一些图表
共享演示 table 行以便更好地理解
id | sender | amount | status | created_at
1 | Ali | 2 | success | 2022-03-10
1 | Hasan | 1 | success | 2022-03-10
1 | Ali | 1 | failed | 2022-03-10
1 | Hasan | 5 | failed | 2022-03-11
1 | Yousuf | 1 | success | 2022-03-11
我想编写一个查询来获取过去 10 天
每个状态统计的所有记录
所以最终结果会更像
2022-03-10
成功:3
失败:1
2022-03-11
成功:1
失败:5
为了更好地理解,我已经对其进行了格式化,但如果我获得过去 10 天的数据,我还可以
所以总共会有 20 行,包括(10 次成功计数 + 10 次失败计数)
现在我 运行 20 个查询来计算过去 10 天的数量,具有 2 个不同的状态,这适用于每个用户,因此会在服务器上产生负载
Select count(*) as aggregate from history where sender = 'Ali' and status= 'sender' and day(created_at) = '10'
Select count(*) as aggregate from history where sender = 'Ali' and status= 'failed' and day(created_at) = '10'
.
.
.
Select count(*) as aggregate from history where sender = 'Ali' and status= 'sender' and day(created_at) = '1'
Select count(*) as aggregate from history where sender = 'Ali' and status= 'failed' and day(created_at) = '1'
要获取最近10天每个状态统计的所有记录,需要根据current_date获取最近10天的where条件,试试:
select created_at,
sum(case when status='success' then amount end) as success,
sum(case when status='failed' then amount end) as failed
from history
WHERE created_at >= DATE_ADD(CURDATE(), INTERVAL -10 DAY)
group by created_at;
Result:
created_at success failed
2022-03-10 3 1
2022-03-11 1 5
我有一个 Laravel 仪表板,它根据两个不同的状态 activity 从该用户填充过去 10 天的一些图表
共享演示 table 行以便更好地理解
id | sender | amount | status | created_at
1 | Ali | 2 | success | 2022-03-10
1 | Hasan | 1 | success | 2022-03-10
1 | Ali | 1 | failed | 2022-03-10
1 | Hasan | 5 | failed | 2022-03-11
1 | Yousuf | 1 | success | 2022-03-11
我想编写一个查询来获取过去 10 天
每个状态统计的所有记录所以最终结果会更像
2022-03-10 成功:3 失败:1
2022-03-11 成功:1 失败:5
为了更好地理解,我已经对其进行了格式化,但如果我获得过去 10 天的数据,我还可以 所以总共会有 20 行,包括(10 次成功计数 + 10 次失败计数)
现在我 运行 20 个查询来计算过去 10 天的数量,具有 2 个不同的状态,这适用于每个用户,因此会在服务器上产生负载
Select count(*) as aggregate from history where sender = 'Ali' and status= 'sender' and day(created_at) = '10'
Select count(*) as aggregate from history where sender = 'Ali' and status= 'failed' and day(created_at) = '10'
.
.
.
Select count(*) as aggregate from history where sender = 'Ali' and status= 'sender' and day(created_at) = '1'
Select count(*) as aggregate from history where sender = 'Ali' and status= 'failed' and day(created_at) = '1'
要获取最近10天每个状态统计的所有记录,需要根据current_date获取最近10天的where条件,试试:
select created_at,
sum(case when status='success' then amount end) as success,
sum(case when status='failed' then amount end) as failed
from history
WHERE created_at >= DATE_ADD(CURDATE(), INTERVAL -10 DAY)
group by created_at;
Result:
created_at success failed 2022-03-10 3 1 2022-03-11 1 5