簡體   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