【问题标题】:sql (oracle) counting number of overlapping intervalssql(oracle)计算重叠间隔的数量
【发布时间】:2018-09-25 20:36:16
【问题描述】:

我有以下问题:

给定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   |
+----+------+-------+------+

我想找出所有具有相同nameid 的重叠间隔(包括端点)[开始,停止] n_overlap 的数量,即:

+----+------+-------+------+-----------+
| id | name | start | stop | n_overlap |
+----+------+-------+------+-----------+
| 1  |   A  |   1   |  5   |     3     |
+----+------+-------+------+-----------+
| 2  |   A  |   2   |  6   |     3     |
+----+------+-------+------+-----------+
| 3  |   A  |   4   |  8   |     3     |
+----+------+-------+------+-----------+
| 4  |   A  |   9   |  10  |     1     |
+----+------+-------+------+-----------+
| 5  |   B  |   3   |  6   |     2     |
+----+------+-------+------+-----------+
| 6  |   B  |   4   |  8   |     2     |
+----+------+-------+------+-----------+
| 7  |   B  |   1   |  2   |     1     |
+----+------+-------+------+-----------+

【问题讨论】:

    标签: sql oracle intervals


    【解决方案1】:

    一种方法使用相关子查询:

    select t.*,
           (select count(*)
            from test t2
            where t2.name = t.name and
                  t2.start < t.end and
                  t2.end > t.start
           ) as num_overlaps
    from test t;
    

    【讨论】:

    • where 中的最后一个条件实际上应该是t2.end &gt; t.start
    • @MarcoC 。 . .谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    相关资源
    最近更新 更多