查询以获取基于时间间隔的计数值

时间:2019-02-12 04:12:52

标签: mysql sql database database-design relational-database

我有这样的桌子:

p_central_ticket
================
- t_id              ======>   id ticket
- t_open_by         ======>   name that raise the ticket
- t_closed_by       ======>   name that closed the ticket 
- t_open_time       ======>   open ticket time
- t_closed_time     ======>   closed ticket time

如果我想显示对所有按名称关闭的票以及今天,每周,每月和每年的关闭时间进行计数,该怎么办?就是这样:

    Name                today      weekly     monthly     yearly     
=================================================================   
test1@random.com         2           10          70        1000         
test2@random.com         5           14          60        1234

样本数据:

t_id      t_open_by      t_closed_by       t_open_time        t_closed_time
===========================================================================
 1     amir@random.com   test1@random.com   2018-03-28          2018-03-29
 2     tiki@random.com   test1@random.com   2018-04-28          2018-05-29

需要帮助的人... 谢谢

3 个答案:

答案 0 :(得分:0)

类似的东西:

SELECT `t_closed_by`,
  COUNT( case when `t_closed_time` > curdate() - interval '1' day THEN 1 END ) as today,
  COUNT( case when `t_closed_time` > curdate() - interval '7' day THEN 1 END ) as weekly,
  COUNT( case when `t_closed_time` > curdate() - interval '1' month THEN 1 END ) as monthly,
  COUNT( case when `t_closed_time` > curdate() - interval '1' year THEN 1 END ) as yearly
FROM Table1
GROUP BY `t_closed_by`

演示:http://sqlfiddle.com/#!9/3d792/11

答案 1 :(得分:0)

在MySQL中可以使用以下类似的方法:(请注意,如果有任何错误,请检查语法。)

SELECT a1.t_closed_by as Name,
    (SELECT COUNT(*) FROM p_central_ticket WHERE t_closed_time = CURDATE() and t_closed_by = a1.t_closed_by) as today,
    (SELECT COUNT(*) FROM p_central_ticket WHERE t_closed_time > DATE_SUB(CURDATE(), INTERVAL 7 DAY) and t_closed_by = a1.t_closed_by) as weekly,
    (SELECT COUNT(*) FROM p_central_ticket WHERE t_closed_time > DATE_SUB(CURDATE(), INTERVAL 30 DAY) and t_closed_by = a1.t_closed_by) as monthly,
    (SELECT COUNT(*) FROM p_central_ticket WHERE t_closed_time > DATE_SUB(CURDATE(), INTERVAL 365 DAY) and t_closed_by = a1.t_closed_by) as yearly
FROM (SELECT DISTINCT t_closed_by FROM p_central_ticket) a1 ;

答案 2 :(得分:0)

您可以使用此方法以偶数分钟的时间间隔从表中获取记录

 SELECT column1,column2,.... FROM tableName
    WHERE
        (DateAndTime BETWEEN '2019-02-11 14:00' AND '2019-02-12 22:00')
    AND
        (DATEPART(MINUTE, DateAndTime) % 60 = 0)