计算日期上存在的记录数

时间:2017-05-18 15:57:52

标签: mysql sql date reporting

我正在尝试计算一个时间段内的不同记录数,按天分组/总计。

在此示例中,客户服务票证在特定日期打开,然后在以后关闭。我试图在每个日子里找出在任何时间点打开了多少张门票(否则,closed status将来相对于那个日期)。这是我在MySQL中使用的查询:

SELECT `cal`.`dt`,
   COUNT(DISTINCT `sub_query`.`id`)
FROM `calendar_table` AS `cal`
LEFT JOIN
  (SELECT `inc`.`id`,
      `inc`.`created_at`,
      `inc_stat`.`updated_at`
   FROM `incidents` AS `inc`
   JOIN `incident_statuses` AS `inc_stat` ON `inc_stat`.`incident_id` = 
`inc`.`id`
   WHERE `inc_stat`.`status` LIKE 'Closed') AS `sub_query` ON (`sub_query`.`created_at` >= `cal`.`dt` AND `sub_query`.`updated_at` <= `cal`.`dt`)

 WHERE `cal`.`dt` >= '2017-01-01'
 AND `cal`.`dt` <= NOW()
 GROUP BY `cal`.`dt`

日历表只是一个“帮助者”表格,具有2010-2020日期格式正确的日期。

示例calendar_table cal数据

id       dt
1        2017-01-01
2        2017-01-02
3        2017-01-03
...      ...

示例事件数据

id     created_at
1      2017-01-01 08:45:01
1      2017-01-01 08:55:01
...    ...

示例incident_statuses inc_stat数据

id        incident_id      status         updated_at
1         1                Closed         2017-01-02
2         2                Closed         2017-01-04
...       ...              ...            ...

子查询正在以这种格式正确生成数据:

id         created_at         updated_at
1          2017-01-01         2017-01-02
2          2017-01-01         2017-01-04
3          2017-01-04         2017-01-05

我想要的输出是这样的:

dt                    count(distinct `subquery`.`id`)
2017-01-01            2            
2017-01-02            2
2017-01-03            1
2017-01-04            3
2017-01-05            1

我意识到在使用FOR循环的编程语言中这会更简单,但有没有人有关于如何仅使用SQL执行此操作的指导?

2 个答案:

答案 0 :(得分:1)

我不确定您使用的是哪个数据库,但我认为您只需要相应的内容:

SELECT CONVERT(date,inc.created_at), COUNT(*)
  FROM incidents inc
 WHERE inc.created_at BETWEEN '2017-01-01' AND NOW()
 GROUP BY CONVERT(date,inc.created_at)
 ORDER BY 1

答案 1 :(得分:0)

试试这个:

SELECT 
    cal.dt
    , COUNT(IFNULL(inc_stat.id, 0)) as cntIncStat
FROM calendar_table AS cal
LEFT JOIN incidents AS inc ON inc.created_at = cal.dt
LEFT JOIN incident_statuses AS inc_stat ON inc_stat.incident_id = inc.id
GROUP BY cal.dt
HAVING
    inc_stat.status = 'Closed'
    AND cal.dt >= '2017-01-01'
    AND cal.dt <= NOW()
;