SQL Server select语句的日期范围?

时间:2011-07-13 06:22:57

标签: sql-server datetime select

我有一个包含数千个条目的数据库,它有两个日期/时间字段,让我们称它们为In和Out:

In                                      Out
2011-06-16 13:45:11.000    2011-06-16 13:49:12.000
2011-06-16 13:51:31.000    2011-06-16 14:23:17.000
2011-06-16 14:51:54.000    2011-06-16 14:58:43.000

依旧......

在输入上我有一个时间范围(timeIn和timeOut)。在输出中,我需要知道落入此时间范围的每个记录中“入”和“出”时间之间的累计秒数。用这个daigram更容易说明:

http://i150.photobucket.com/albums/s99/dc2000_bucket/sql_graph.jpg

从图中取名,我需要知道“时间间隔1(以秒为单位)”+“时间间隔2(以秒为单位)”+“时间间隔3(以秒为单位)”。如何撰写这样的SQL语句?

2 个答案:

答案 0 :(得分:2)

select sum(datediff(second, [In], case when @TimeOut < [Out] 
                                    then @TimeOut 
                                    else [Out] 
                                  end))
from YourTable
where [In] between @TimeIn and @TimeOut

或者像这样,如果你想包含在@TimeIn - @TimeOut中结束的间隔。

select sum(datediff(second, case when @TimeIn < [In] 
                              then [In]
                              else @TimeIn
                            end, 
                            case when @TimeOut < [Out] 
                              then @TimeOut 
                              else [Out] 
                            end))
from YourTable
where [In] <= @TimeOut and 
      [Out] >= @TimeIn

答案 1 :(得分:1)

SQL-Server中没有GREATEST()LEAST()函数,或者它会是这样的:

SELECT LEAST(t.timeOut, @TimeOut) - GREATEST(t.timeIn,@TimeIn) 
FROM tableX AS t
WHERE t.timeIn <= @TimeOut
  AND @TimeIn <= t.timeOut

使用CASE

SELECT DATEDIFF( second
               , CASE WHEN t.timeIn <= @TimeIn
                        THEN @TimeIn
                        ELSE t.timeIn
                 END
               , CASE WHEN t.timeOut <= @TimeOut
                        THEN t.timeOut
                        ELSE @TimeOut
                 END 
               )
       AS TimeInterval 
FROM tableX AS t
WHERE t.timeIn <= @TimeOut
  AND @TimeIn <= t.timeOut
ORDER BY t.timeIn