我想从“tData”中获取记录,其中FooTime列值在临时时间范围表“tTime”
中tData table:
FooTime Value 2010-01-01 00:15 3 2010-01-01 00:30 2 2010-01-01 00:45 4 2010-01-01 01:00 5 2010-01-01 01:15 1 2010-01-01 01:30 3 2010-01-01 01:45 4 2010-01-01 02:00 12 2010-01-01 02:15 13 2010-01-01 02:30 12 2010-01-01 02:45 14 2010-01-01 03:00 15 2010-01-01 03:15 3 2010-01-01 03:30 2 2010-01-01 03:45 3 2010-01-01 04:00 5 .......... .......... .......... 2010-01-02 00:15 3 2010-01-02 00:30 2 2010-01-02 00:45 4 2010-01-02 01:00 5 2010-01-02 01:15 1 2010-01-02 01:30 3 2010-01-02 01:45 4 2010-01-02 02:00 12 2010-01-02 02:15 13 2010-01-02 02:30 12 2010-01-02 02:45 14 2010-01-02 03:00 15 2010-01-02 03:15 3 2010-01-02 03:30 2 2010-01-02 03:45 3 2010-01-02 04:00 5 .......... .......... ..........
tTime table:
StartTime EndTime 2010-01-01 02:00 2010-01-01 06:00 2010-01-02 02:00 2010-01-02 06:00 .... .... ....
根据上面的示例数据,应该返回以下记录,因为时间:
FooTime Value 2010-01-01 02:00 12 2010-01-01 02:15 13 2010-01-01 02:30 12 2010-01-01 02:45 14 2010-01-01 03:00 15 2010-01-01 03:15 3 2010-01-01 03:30 2 2010-01-01 03:45 3 2010-01-01 04:00 5 ... ... 2010-01-01 06:00 3 2010-01-02 02:00 12 2010-01-02 02:15 13 2010-01-02 02:30 12 2010-01-02 02:45 14 2010-01-02 03:00 15 2010-01-02 03:15 3 2010-01-02 03:30 2 2010-01-02 03:45 3 2010-01-02 04:00 5 ... ... 2010-01-02 06:00 3
请考虑不同日期的时间范围可能会有所不同,例如: tTime表:
StartTime EndTime 2010-01-01 02:00 2010-01-01 06:00 2010-01-02 19:00 2010-01-02 24:00 .... .... ....
答案 0 :(得分:2)
我不在我的计算机附近使用MS SQL,但这应该可以解决问题:
SELECT tData.*
FROM
tData
LEFT JOIN tTime
ON CONVERT(VARCHAR(10), tTime.StartTime, 101) = CONVERT(VARCHAR(10), tData.FooTime, 101)
WHERE
tData.FooTime BETWEEN tTime.StartTime AND tTime.EndTime
基本上根据StartTime和FooDate的Date(没有时间)部分连接两个表,然后在WHERE子句中使用BETWEEN。
正如我所说,我不能在这台笔记本电脑上测试这个,但我会说它能够正常工作。
编辑:假设根据您的示例,tTime表中每行只有1天
编辑:记得你应该能够在JOIN标准中使用BETWEEN,所以这应该更好:
SELECT tData.*
FROM
tData
INNER JOIN tTime
ON tData.FooTime BETWEEN tTime.StartTime AND tTime.EndTime
答案 1 :(得分:1)
SELECT FooTime, Value
FROM tData INNER JOIN tTime
ON (tData.FooTime >= tTime.StartTime AND tData.EndTime <= tTime.StopTime)
我不记得在join子句中是否允许Between,但如果是:
SELECT FooTime, Value
FROM tData INNER JOIN tTime
ON (tData.FooTime BETWEEN tTime.StartTime AND tData.EndTime)