表A交易明细
TTime (datetime), TableAValues, TableAValues, <etc>...
表B相关表
ID, DateTimeStart (datetime), DateTimeEnd (datetime), TableBValues, TableBValues, <etc>...
我需要一种方法来返回一行信息,其中包括所有TableAValues以及TTime表A落在表B的DateTimeStart和DateTimeEnd之间的所有TableBValues。
答案 0 :(得分:0)
SELECT *
FROM TableA AS A
JOIN TableB AS B
ON A.TTime BETWEEN B.DateTimeStart AND B.DateTimeEnd
请注意,BETWEEN
具有包容性,这意味着如果A.TTime
与B.StartDateTime
或B.EndDateTime
相同,则会返回true。如果您想获得真正落在开始和结束之间的那些,那么您应该使用大于>
且少于<
个运算符。
您还应该了解SQL Server的准确性,每MSDN,DateTime是
舍入为.000,.003或.007秒的增量
运行以下查询有助于说明:
DECLARE @StartTime DATETIME = '2016-01-01 00:00:00.000',
@TestTime DATETIME = '2016-01-01 08:00:00.008', -- rounds down to .007
@EndTime1 DATETIME = '2016-01-01 08:00:00.007', -- stays the same
@EndTime2 DATETIME = '2016-01-01 08:00:00.006'; -- rounds up to .007
SELECT 'Eh? What just happened?'
WHERE @TestTime BETWEEN @Starttime AND @EndTime1;
SELECT 'What is going on!'
WHERE @TestTime BETWEEN @Starttime AND @EndTime2;