1

我有带有 astartTime和 a 的单位endTime。在另一个单元之后开始并在另一个单元到达终点之前结束的单元已通过该单元。我想计算每个单元通过多少个单元以及每个单元通过了多少个单元。

我的表如下所示:

id; startTime; endTime 
3;  1;          2
1;  1;          8
2;  2;          3
5;  2;          9
4;  2;          5
6;  3;          4

结果应该是这样的:

id; passed; passed_by
3;  0;        0
1;  0;        3
2;  1;        0
5;  0;        1
4;  1;        1
6;  3;        0
4

3 回答 3

2
SELECT id, 
       passed = (SELECT Count(*) 
               FROM   dbo.tablename T2 
               WHERE  T2.id <> T1.id 
                      AND T2.starttime < T1.starttime 
                      AND T2.endtime   > T1.endtime), 
       passed_by = (SELECT Count(*) 
               FROM   dbo.tablename T2 
               WHERE  T2.id <> T1.id 
                      AND T2.starttime > T1.starttime 
                      AND T2.endtime   < T1.endtime) 
FROM   dbo.tablename T1 

演示

ID    PASSED    PASSED_BY
3       0          0
1       0          3
2       1          0
5       0          1
4       1          1
6       3          0
于 2013-05-22T21:32:42.723 回答
1
select t1.id, 
sum (case when t1.startTime < t2.startTime and t1.endTime > t2.endTime then 1 else 0 end) as passed_by,
sum(case when t1.startTime > t2.startTime and t1.endTime < t2.endTime then 1 else 0 end) as passed
from Table1 t1
inner join Table1 t2 on t1.id <> t2.id
group by t1.id

SqlFiddle

于 2013-05-22T21:40:37.187 回答
0
SELECT
    id ,
    passed =
    (
       select count(rr.id) from race r
        join race rr ON r.id != rr.id
        where (r.start > rr.start) and (r.[end] < rr.[end]) and r.id = ro.id
    ) ,
    passedby =
    (
       select count(rr.id) from race r
        join race rr ON r.id != rr.id
        where (r.start < rr.start) and (r.[end] > rr.[end]) and r.id = ro.id
    )
  FROM race ro
于 2013-05-22T22:12:05.103 回答