迭代这个表的好方法?

时间:2011-12-27 11:21:42

标签: sql-server

我有这样的表:

ID Name Date StartTime EndTime SomeOtherID
1 Mark 2011-11-25 15:00 17:00 1
1 Tom  2011-11-26 17:00 19:00 1
1 Jack 2011-11-27 20:00 22:00 1

我需要这样做

select * from other table 
Where ID=1
AND( 
(Date = 2011/12/25 and time between 15:00 and 17:00) 
OR (Date =2011/12/26 and time between 17:00 and 19:00)
OR (Date =2011/12/27 and time between 19:00 and 21:00)
)

我需要为SomeOtherID = 1的每一行执行此操作,对于未知行数(可能是2,可能是30,因此我不能使用固定数量的参数)。

希望这个问题可以理解。

2 个答案:

答案 0 :(得分:3)

试试这个:

SELECT * 
FROM other_table ot
INNER JOIN (SELECT Date, StartTime, EndTime 
            FROM first_table
            WHERE SomeOtherID = 1
           ) ft ON ot.Date = ft.Date AND ot.Time BETWEEN (ft.StartTime, ft.EndTime)
WHERE ID=1;

答案 1 :(得分:0)

试试这个

Select * 
from SomeTable 
where Time between StartTime and EndTime 
and Date = Date
AND SomeOtherID = 1