【问题标题】:Calculate open cases per day计算每天的未结案件
【发布时间】:2020-08-16 01:01:05
【问题描述】:

我正在处理基于时间的查询,我希望获得计算白天打开案例的最佳方法。我确实有表task_interval,它有两列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 date datetime group-by window-functions


    【解决方案1】:

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

    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


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

    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
    

    Demo on DB Fiddle - 两个查询都产生:

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

    【讨论】:

    • 很遗憾我正在运行 5.7 MySQL ;/
    • @yerpy:好的,我用早期版本的解决方案更新了我的答案。
    • 我有一个巨大的要求。我试图弄清楚。您能否简要介绍一下嵌套子查询,它是如何工作的?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 2020-11-16
    • 2019-02-08
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多