-1

我有两张桌子。

地图

Product    Channel  ProgDate   AdvTime
Air    Pix  30-04-2011  20:57:16
Air    Pix  30-05-2011  00:55:08

工商管理硕士

Product    Channel Date   ProgStartTime ProgEndTime
Air    Pix  30-04-2011  23:00:00   02:00:00
Air    Pix  30-04-2011  21:00:00   22:00:00

我必须检查 MAP 中的 AdvtTime 是否在 MBA 表中的StartTime&之间。EndTime

但是当持续时间(ProgStartTime- ProgEndTime)为一小时时,我需要 + 或 - 5 分钟的缓冲区。

00:05:08 to match 23:00:00需要,02:00:00并且 。20:57:16 to match 21:00:0022:00:00

我使用以下查询加入

Select Distinct mb.Id as mbaid,mp.id as mapid, mp.Channel as Channel, mp.Product,mp.ProgDate, mp.AdvTime, mb.Channel,  mb.ProgStartTime, 
  mb.ProgEndTime, convert(time, dateadd(minute, datediff(minute, mb.progStartTime, mb.progEndTime), 0)) as timeDiff from map22 as mp inner join mba22 as mb 
on ((mp.ProgDate = mp.ProgDate and mp.Channel=mb.Channel and mp.Product=mb.Product)) 
 where (mp.ProgDate = mb.ProgDate
           AND AdvTime >= ProgStartTime
           AND (AdvTime <= ProgEndTime OR ProgEndTime < ProgStartTime))
          OR
          (mp.ProgDate = Dateadd(day,1,mb.ProgDate)
           AND ProgEndTime < ProgStartTime
           AND AdvTime <= ProgEndTime)
order by  mp.Id asc 
4

1 回答 1

0
Select  Distinct mb.Id as mbaid,
        mp.id as mapid, 
        mp.Channel as Channel, 
        mp.Product,
        mp.ProgDate, 
        mp.AdvTime, 
        mb.Channel,  
        mb.ProgStartTime, 
        mb.ProgEndTime, 
        convert(time, dateadd(minute, datediff(minute, mb.progStartTime, mb.progEndTime), 0)) as timeDiff 
From    map22 as mp 
Inner   Join mba22 as mb 
        on  mp.ProgDate = mp.ProgDate 
        and mp.Channel= mb.Channel 
        and mp.Product= mb.Product
Where   mp.ProgDate = mb.ProgDate
And     Convert(DateTime,ProgDate) + Convert(DateTime,AdvTime)
            Between 
            Case 
            When ProgEndTime < ProdStartTime And DateDiff(hh,ProgEndTime,ProgStartTime) > 23 Then DateAdd(mi,-5,Convert(DateTime,[Date]) + Convert(DateTime,ProgStartTime))
            When ProgEndTime > ProdStartTime And DateDiff(hh,ProgStartTime,ProgEndTime) > 1 Then DateAdd(mi,-5,Convert(DateTime,[Date]) + Convert(DateTime,ProgStartTime)) 
            Else Convert(DateTime,[Date]) + Convert(DateTime,ProgStartTime) End
            And 
            Case 
            When ProgEndTime < ProdStartTime And DateDiff(hh,ProgEndTime,ProgStartTime) > 23 Then DateAdd(mi,5,Convert(DateTime,Case When ProgEndTime < ProdStartTime Then DateAdd(dd,1,[Date]) Else [Date] End) + Convert(DateTime,ProgEndTime))  
            When ProgEndTime > ProdStartTime And DateDiff(hh,ProgStartTime,ProgEndTime) > 1 Then DateAdd(mi,5,Convert(DateTime,Case When ProgEndTime < ProdStartTime Then DateAdd(dd,1,[Date]) Else [Date] End) + Convert(DateTime,ProgEndTime))  
            Else (Case When ProgEndTime < ProdStartTime Then DateAdd(dd,1,Convert(DateTime,[Date])) Else Convert(DateTime,[Date]) End) + Convert(DateTime,ProgEndTime) End
Order By mp.Id Asc 
于 2013-03-18T17:58:40.817 回答