简体   繁体   English

MySQL查询-在一段时间内按状态和日期分组?

[英]mySQL query - group by status & day, for a certain period?

We have a table which inserts a new row each time something happens. 我们有一个表格,每当发生某种情况时,都会插入一个新行。

We basically want to do a 7, 14, 28 day thing based on the query: 我们基本上想根据查询做7、14、28天的事情:

We want to work with these fields: 我们想与这些领域合作:

status, time (datetime)

We basically want to group by the day, and echo a count for each day: 我们基本上想按天分组,并回显每天的计数:

5th October
Completed   5,292
Aborted 19
Failed 1

4th October
Completed   5,292
Aborted 19
Failed 1

3rd October
Completed   5,292
Aborted 19
Failed 1

Kind of like this, so it groups by day, and shows it by status and count . 有点像这样,所以它按天分组,并按statuscount

There are only 3 statuses, the ones listed: completed, aborted, failed 只有3种状态,列出的状态:已完成,已中止,失败

We want to get the counts for each of these statuses, and group them by status and by day - for a certain day range, example: 7, 14, 21, 28 我们想要获取每个状态的计数,并按状态和日期将它们分组-在特定的日期范围内,例如:7、14、21、28

How can we do this using SQL? 我们如何使用SQL做到这一点? I remember doing something like this a long time ago. 我记得很久以前就做过这样的事情。

something like this should help you: 这样的事情应该可以帮助您:

Declare @StartDate as smalldatetime
Declare @range as int

set @StartDate = getDate() --or whatever else you want to use
set @range = 7

Select status, Count(time)
Group By status
where time >= dateadd(dd, -@range, @StartDate)

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

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