引用与 Max() 结果相邻的另一个 table 和 return 数据

Refer to another table and return data adjacent to Max() result

我有以下两个 table:

使用 SQL Server 2012,我想知道每小时 table 中的 INTERVAL,其中 MaxWaitTimeSplit 匹配来自 [=每天 16=] table。我假设我需要在这里使用 window function,但我无法找出正确的答案。

有时 MaxWaitTime 一整天都是 0,因此 hourly table 中的所有行都匹配。在这种情况下,我更喜欢 Null 答案,但当天最早的 INTERVAL 就可以了。

有时也会出现多个 INTERVALs 等待时间相同的情况。在这种情况下,应返回当天出现 MaxWaitTime 的第一个 INTERVAL

看起来简单的左联接应该可以在表之间工作。我只是根据上面显示的数据...

查询应如下所示。如果连接失败,则返回 NULL。试一试..

select daily.* ,hourly.callsoffered, hourly.interval as maxinterval

from daily

left join hourly 
   on convert(date,hourly.interval) = daily.row_date
     and hourly.split = daily.split
     and hourly.maxwaittime = daily.maxwaittime

如果您最多需要一个匹配项,您可以使用 outer apply

看起来简单的左联接应该可以在表之间工作。我只是根据上面显示的数据...

查询应如下所示。如果连接失败,则返回 NULL。试试吧..

select d.*, h.interval as maxinterval
from daily d outer apply
     (select top 1 h.*
      from hourly h
      where convert(date, h.interval) = d.row_date and
            h.split = d.split and
            h.maxwaittime = d.maxwaittime
      order by h.interval asc
     ) h;

如果你想 NULL 进行多场比赛,你可以做类似的事情:

select d.*, h.interval as maxinterval
from daily d outer apply
     (select top 1 h.callsoffered, h.split, max(h.interval) as maxinterval
      from hourly h
      where convert(date, h.interval) = d.row_date and
            h.split = d.split and
            h.maxwaittime = d.maxwaittime
      group by h.maxwaittime, h.split
      having count(*) = 1
     ) h;