如何每7天计算记录数和按日期分组SQL

时间:2019-04-08 14:33:49

标签: mysql sql

我正在尝试编写一个查询,该查询计算每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

这将返回

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

我希望结果像

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

仅通过查询就能做到吗,还是我也必须使用JavaScript? 我在mysql上使用phpmyadmin

谢谢您的建议

2 个答案:

答案 0 :(得分:1)

如果您对给定一周开始的边缘条件不太挑剔,则可以使用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);

此答案假设您的数据每周至少有一个数据点。如果可能存在很大的差距,那么一种解决方案是将日历表加入其中。这是如何执行此操作的示例:

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提供了几种生成日历表的方式,例如上面第二个查询中使用的方式。

答案 1 :(得分:0)

一种方法使用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);