MySQL 如何通过组合计算并发事件的频率?
How to compute frequency of concurrent events by combination in MySQL?
我正在寻找一种方法来识别同时发生的事件名称名称:即,将事件名称与相同的开始 (startts) 和结束 (endts) 时间相关联:事件完全并发(部分重叠不是此数据库的一个功能)。
玩具数据框
+------------------+
|name startts endts|
| A 02:20 02:23 |
| A 02:23 02:25 |
| A 02:27 02:28 |
| B 02:20 02:23 |
| B 02:23 02:25 |
| B 02:25 02:27 |
| C 02:27 02:28 |
| D 02:27 02:28 |
| D 02:28 02:31 |
| E 02:27 02:28 |
| E 02:29 02:31 |
+------------------+
理想输出:
+---------------------------+
|combination| count |
+---------------------------+
| AB | 2 |
| AC | 1 |
| AE | 1 |
| AD | 1 |
| BC | 0 |
| BD | 0 |
| BE | 0 |
| CE | 0 |
+-----------+---------------+
当然,我会尝试循环,但我认识到 mysql 服务器不是最佳选择。
我尝试过的是通过选择不同的名称和开始和结束组合然后在 table 本身(选择名称)上进行左连接来生成临时 table。
谢谢。
我将其理解为 self-join、聚合和匹配间隔的条件计数:
select t1.name name1, t2.name name2,
sum(t1.startts = t2.startts and t1.endts = t2.endts) cnt
from mytable t1
inner join mytable t2 on t2.name > t1.name
group by t1.name, t2.name
order by t1.name, t2.name
name1 | name2 | cnt
:---- | :---- | --:
A | B | 2
A | C | 1
A | D | 1
A | E | 1
B | C | 0
B | D | 0
B | E | 0
C | D | 1
C | E | 1
D | E | 1
请注意,如果您要查找 重叠 间隔的计数,您只需将 sum()
更改为:
sum(t1.startts <= t2.endts and t1.endts >= t2.startts) cnt
我正在寻找一种方法来识别同时发生的事件名称名称:即,将事件名称与相同的开始 (startts) 和结束 (endts) 时间相关联:事件完全并发(部分重叠不是此数据库的一个功能)。
玩具数据框
+------------------+
|name startts endts|
| A 02:20 02:23 |
| A 02:23 02:25 |
| A 02:27 02:28 |
| B 02:20 02:23 |
| B 02:23 02:25 |
| B 02:25 02:27 |
| C 02:27 02:28 |
| D 02:27 02:28 |
| D 02:28 02:31 |
| E 02:27 02:28 |
| E 02:29 02:31 |
+------------------+
理想输出:
+---------------------------+
|combination| count |
+---------------------------+
| AB | 2 |
| AC | 1 |
| AE | 1 |
| AD | 1 |
| BC | 0 |
| BD | 0 |
| BE | 0 |
| CE | 0 |
+-----------+---------------+
当然,我会尝试循环,但我认识到 mysql 服务器不是最佳选择。
我尝试过的是通过选择不同的名称和开始和结束组合然后在 table 本身(选择名称)上进行左连接来生成临时 table。
谢谢。
我将其理解为 self-join、聚合和匹配间隔的条件计数:
select t1.name name1, t2.name name2,
sum(t1.startts = t2.startts and t1.endts = t2.endts) cnt
from mytable t1
inner join mytable t2 on t2.name > t1.name
group by t1.name, t2.name
order by t1.name, t2.name
name1 | name2 | cnt :---- | :---- | --: A | B | 2 A | C | 1 A | D | 1 A | E | 1 B | C | 0 B | D | 0 B | E | 0 C | D | 1 C | E | 1 D | E | 1
请注意,如果您要查找 重叠 间隔的计数,您只需将 sum()
更改为:
sum(t1.startts <= t2.endts and t1.endts >= t2.startts) cnt