繁体   English   中英

计算每天的未结案件

[英]Calculate open cases per day

我正在处理基于时间的查询,我想获得计算白天打开案例的最佳方法。 我确实有表task_interval有 2 列startend

JSON 示例:

[
    {
        "start" : "2019-10-15 20:41:38",
        "end" : "2019-10-16 01:44:03"
    },
    {
        "start" : "2019-10-15 20:43:52",
        "end" : "2019-10-15 22:18:54"
    },
    {
        "start" : "2019-10-16 20:21:38",
        "end" : null,
    },
    {
        "start" : "2019-10-17 01:42:35",
        "end" : null
    },
    {
        "create_time" : "2019-10-17 03:15:57",
        "end_time" : "2019-10-17 04:14:17"
    },
    {
        "start" : "2019-10-17 03:16:44",
        "end" : "2019-10-17 04:14:31"
    },
    {
        "start" : "2019-10-17 04:15:23",
        "end" : "2019-10-17 04:53:28"
    },
    {
        "start" : "2019-10-17 04:15:23",
        "end" : null,
    },
]

查询结果应返回:

[
    { time: '2019-10-15', value: 1 },
    { time: '2019-10-16', value: 1 }, // Not 2! One task from 15th has ended
    { time: '2019-10-17', value: 3 }, // We take 1 continues task from 16th and add 2 from 17th which has no end in same day
]

我已经编写了查询,它将返回结束日期与开始日期不同的开始任务的累积总和:

SELECT 
    time,
    @running_total:=@running_total + tickets_number AS cumulative_sum
FROM
    (SELECT 
        CAST(ti.start AS DATE) start,
            COUNT(*) AS tickets_number
    FROM
        ticket_interval ti
    WHERE
        DATEDIFF(ti.start, ti.end) != 0
            OR ti.end IS NULL
    GROUP BY CAST(ti.start AS DATE)) X
        JOIN
    (SELECT @running_total:=0) total;    

如果您正在运行 MySQL 8.0,则一种选择是取消透视,然后聚合并执行 window 总和以计算运行计数:

select 
    date(dt) dt_day, 
    sum(sum(no_tasks)) over(order by date(dt)) no_tasks 
from (
    select start_dt dt, 1 no_tasks from mytable
    union all select end_dt, -1 from mytable where end_dt is not null
) t
group by date(dt)
order by dt_day

旁注: startend是保留字,因此列名不是很好的选择。 我将它们重命名为start_dtend_dt


在早期版本中,我们可以使用用户变量模拟 window 和,如下所示:

select 
    dt_day, 
    @no_tasks := @no_tasks + no_tasks no_tasks 
from (
    select date(dt) dt_day, sum(no_tasks) no_tasks
    from (
        select start_dt dt, 1 no_tasks from mytable
        union all select end_dt, -1 from mytable where end_dt is not null
    ) t
    group by dt_day
    order by dt_day
) t
cross join (select @no_tasks := 0) x
order by dt_day

DB Fiddle 上的演示- 两个查询都产生:

dt_day     | no_tasks
:--------- | -------:
2019-10-15 |        1
2019-10-16 |        1
2019-10-17 |        3

暂无
暂无

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

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