我有两张桌子。
Product Channel Date Advt Time
Air Pix 30-04-2011 22:23:16
Air Pix 30-04-2011 23:55:08
Product Channel Date StartTime EndTime
Air Pix 30-04-2011 22:00:00 01:00:00
Air Pix 30-04-2011 23:00:00 02:00:00
我必须检查MAP中的AdvtTime是否在StartTime和amp;之间。 MBA表中的EndTime。
我使用了以下查询
select distinct *
from MAP
inner join MBA on (MAP.Channel = MBA.Channel
and MAP.Product = MBA.Product
and MAP.ProgDate=MBA.ProgDate)
where AdvtTime between ti and tii
order by Channel asc
但是随着结束时间延长到第二天它没有结果。 请帮助我进一步了解。
我想:
22:23:16
将22:00:00
与01:00:00
和23:55:08
将23:00:00
与02:00:00
匹配。答案 0 :(得分:0)
select distinct *
from MAP
inner join MBA on (MAP.Channel = MBA.Channel
and MAP.Product = MBA.Product
and MAP.ProgDate=MBA.ProgDate)
where (AdvtTime between ti and tii) or (AdvTime between ti and DATEADD(hh, DATEDIFF(HH,AdvTime, tii),tii))
order by Channel asc
答案 1 :(得分:0)
以下查询应该为您提供所需的答案:
SELECT DISTINCT *
FROM MAP
INNER JOIN MBA
ON MAP.Channel = MBA.Channel
AND MAP.Product = MBA.Product
WHERE (MAP.Date = MBA.Progdate
AND AdvtTime >= StartTime
AND (AdvtTime <= EndTime OR EndTime < StartTime))
OR
(MAP.Date = dateadd(DAY,1,MBA.ProgDate) -- extended from yesterday
AND EndTime < StartTime -- iff EndTime < StartTime
AND AdvtTime <= EndTime)
ORDER BY MBA.Channel ASC
请参阅http://www.sqlfiddle.com/#!6/1e49f/1/0进行测试。
但是,最好将日期和时间组合到datetime字段中,然后在需要时提取单独的部分以用于演示目的。
答案 2 :(得分:0)
此外,您可以使用此选项与简单的JOIN
SELECT DISTINCT *
FROM dbo.map m JOIN dbo.mba m2 ON m.Product = m2.Product
AND m.Channel = m2.Channel
AND m.[Date] = m2.[Date]
AND (m.[Advt Time] > m2.[StartTime] AND m2.[StartTime] > m2.[EndTime]
OR m.[Advt Time] BETWEEN m2.[StartTime] AND m2.[EndTime])
SQLFiddle上的演示