【问题标题】:Refer to another table and return data adjacent to Max() result参考另一个表并返回与 Max() 结果相邻的数据
【发布时间】:2018-03-28 12:56:31
【问题描述】:

我有以下两张表:

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

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

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

【问题讨论】:

    标签: sql sql-server tsql sql-server-2012 window-functions


    【解决方案1】:

    如果你想要最多一场比赛,你可以使用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;
    

    【讨论】:

      【解决方案2】:

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

      查询应该是这样的。如果连接失败,则返回 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
      

      【讨论】:

      • 哈利,谢谢你的回复。我还认为左连接最初会这样做,但鉴于上述条件,此解决方案失败 - 当多行匹配时,我在同一天得到多个结果。上面的表格实际上只是插图。
      • 请问您能提供实际数据吗?插图数据表明上述查询应该有效..重复了什么?看起来除了间隔之外,所有数据都在每日表中可用..所以我只是看不到数据是如何被复制的。除非您在不同的时间间隔有相同的最大等待时间..
      猜你喜欢
      • 2011-09-30
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-19
      • 2018-11-23
      • 1970-01-01
      相关资源
      最近更新 更多