[英]How do i count number of records and group by date every 7 days SQL
I am trying to write a query that counts the number of records that were created every 7 days, Using this query i get the number of records created per day, 我正在尝试编写一个查询,该查询计算每7天创建的记录数,使用此查询,我可以获得每天创建的记录数,
SELECT 'Closed' AS `Status`, COUNT(*) AS `Count`, `raisedon` AS `Date` FROM table WHERE raisedon >= '2019-01-01' and raisedon < '2019-03-29' AND status = 'Open' AND type = 'A' AND location = 'B' AND locationid = 'C' GROUP BY raisedon
This returns 这返回
Closed 1 2019-01-01
Closed 1 2019-01-14
Closed 2 2019-01-16
Closed 1 2019-01-24
Closed 1 2019-01-25
Closed 1 2019-01-30
Closed 1 2019-02-01
Closed 1 2019-02-03
Closed 1 2019-02-28
Closed 1 2019-03-07
Closed 1 2019-03-08
I would like the results to be like 我希望结果像
Closed 1 2019-01-01
Closed 1 2019-01-08
Closed 2 2019-01-15
Closed 2 2019-01-22
Closed 3 2019-01-29
Closed 0 2019-02-05
Closed 0 2019-02-12
Closed 0 2019-02-19
Closed 1 2019-02-26
Closed 2 2019-03-05
Is this possible with just a query or will i have to use javascript aswell, I am using phpmyadmin with mysql 这可能只是查询还是我也必须使用javascript,我将phpmyadmin与mysql一起使用
Thanks for any advice 感谢您的任何建议
If you are not too picky about your edge conditions for where a given week starts, you might just be able to aggregate using YEARWEEK
: 如果您对给定一周开始的边缘条件不太挑剔,则可以使用
YEARWEEK
进行汇总:
SELECT
'Closed' AS Status,
COUNT(*) AS cnt,
YEARWEEK(raisedon) AS week
FROM yourTable
WHERE
raisedon >= '2019-01-01' AND raisedon < '2019-03-29' AND
status = 'Open' AND
type = 'A' AND
location = 'B' AND
locationid = 'C'
GROUP BY
YEARWEEK(raisedon);
This answer assumes that your data would have at least one data point present for each week. 该答案假设您的数据每周至少有一个数据点。 If there could be large gaps, then one solution would be to join with a calendar table.
如果可能存在很大的差距,那么一种解决方案是将日历表加入其中。 Here is an example of how to do this:
这是如何执行此操作的示例:
SELECT
'Closed' AS Status,
COUNT(t2.raisedon) AS cnt,
YEARWEEK(t1.raisedon) AS week
FROM
(
SELECT '2019-01-01' AS raisedon UNION ALL
SELECT '2019-01-02' UNION ALL
SELECT '2019-01-03' UNION ALL
...
SELECT '2019-01-31' UNION ALL
SELECT '2019-02-01' UNION ALL
...
SELECT '2019-03-31'
) t1
LEFT JOIN yourTable t2
ON t1.raisedon = t2.raisedon
WHERE
t1.raisedon >= '2019-01-01' AND t1.raisedon < '2019-03-29' AND
t2.status = 'Open' AND
t2.type = 'A' AND
t2.location = 'B' AND
t2.locationid = 'C'
GROUP BY
YEARWEEK(t1.raisedon);
See here for several ways to generate a calendar table like the one used above in the second query. 请参阅此处 ,以了解生成日历表的几种方法,例如上面第二个查询中使用的方法。
One method uses datediff()
: 一种方法使用
datediff()
:
SELECT 'Closed' AS `Status`,
COUNT(*) AS `Count`,
MIN(raisedon) AS `Date`
FROM table
WHERE raisedon >= '2019-01-01' AND
raisedon < '2019-03-29' AND
status = 'Open' AND
type = 'A' AND
location = 'B' AND
locationid = 'C'
GROUP BY FLOOR(DATEDIFF('2019-01-01', raisedon) / 7);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.