Mysql 每天计算未结案件
我正在处理基于时间的查询,我希望得到计算白天打开的案例的最佳方法。我有一个表Mysql 每天计算未结案件,mysql,date,datetime,group-by,window-functions,Mysql,Date,Datetime,Group By,Window Functions,我正在处理基于时间的查询,我希望得到计算白天打开的案例的最佳方法。我有一个表task\u interval,它有两列start和end 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
task\u interval
,它有两列start
和end
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,一个选项是取消PIVOT,然后聚合并执行窗口求和以计算运行计数:
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
旁注:start
和end
是保留字,因此列名不是很好的选择。我将它们重命名为start\u dt
和end\u 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
-两个查询都会产生:
dt_day | no_tasks
:--------- | -------:
2019-10-15 | 1
2019-10-16 | 1
2019-10-17 | 3
dt|U日|无任务
:--------- | -------:
2019-10-15 | 1
2019-10-16 | 1
2019-10-17 | 3
不幸的是,我运行的是5.7MySQL/@耶比:好的,我更新了我的答案,为早期版本提供了解决方案。我有一个巨大的要求。我在想办法。你能简单地告诉我嵌套子查询的工作原理吗?