SQL Query,只有一个表

时间:2013-05-22 21:26:01

标签: sql tsql

我的单位有startTimeendTime。在另一个单位之后开始并在另一个单位到达结束之前结束的单位已通过该单位。我想计算每个单位通过的单位数以及每个单位通过的单位数。

我的表格如下:

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

3 个答案:

答案 0 :(得分: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 

Demo

ID    PASSED    PASSED_BY
3       0          0
1       0          3
2       1          0
5       0          1
4       1          1
6       3          0

答案 1 :(得分: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

答案 2 :(得分: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