【发布时间】:2019-03-04 12:22:15
【问题描述】:
参考以下并正确回答的问题:
sql (oracle) counting number of overlapping intervals
给定oracle sql数据库中的下表test:
+----+------+-------+------+
| id | name | start | stop |
+----+------+-------+------+
| 1 | A | 1 | 5 |
+----+------+-------+------+
| 2 | A | 2 | 6 |
+----+------+-------+------+
| 3 | A | 5 | 8 |
+----+------+-------+------+
| 4 | A | 9 | 10 |
+----+------+-------+------+
| 5 | B | 3 | 6 |
+----+------+-------+------+
| 6 | B | 4 | 8 |
+----+------+-------+------+
| 7 | B | 1 | 2 |
+----+------+-------+------+
我现在想找出重叠间隔的数量(包括端点)[开始,停止]n_overlap 以及所有id 具有相同name 的stop 值的总和,即:
+----+------+-------+------+-----------+------------+
| id | name | start | stop | n_overlap | sum_stops |
+----+------+-------+------+-----------+------------+
| 1 | A | 1 | 5 | 3 | 19 |
+----+------+-------+------+-----------+------------+
| 2 | A | 2 | 6 | 3 | 19 |
+----+------+-------+------+-----------+------------+
| 3 | A | 4 | 8 | 3 | 19 |
+----+------+-------+------+-----------+------------+
| 4 | A | 9 | 10 | 1 | 10 |
+----+------+-------+------+-----------+------------+
| 5 | B | 3 | 6 | 2 | 14 |
+----+------+-------+------+-----------+------------+
| 6 | B | 4 | 8 | 2 | 14 |
+----+------+-------+------+-----------+------------+
| 7 | B | 1 | 2 | 1 | 2 |
+----+------+-------+------+-----------+------------+
我尝试了这个解决方案,它有效:
select t.*,
(select count(*)
from test t2
where t2.name = t.name and
t2.start <= t.stop and
t2.stop >= t.start
) as n_overlap,
(select sum(stop)
from test t2
where t2.name = t.name and
t2.start <= t.stop and
t2.stop >= t.start
) as sum_stops
from test t;
但是,有没有办法压缩两个 select/where 查询,使用例如:
select t.*,
(select count(*) as n_overlap, sum(stop) as sum_stops
from test t2
where t2.name = t.name and
t2.start <= t.stop and
t2.stop >= t.start
)
from test t;
会引发too many values 错误?
【问题讨论】:
标签: sql oracle select count where