如何加入最新更新?

时间:2016-12-08 19:03:08

标签: sql sql-server join

我有两张桌子:

  1. delivery包含uiddtimecandy列,用于记录哪些用户何时获赠糖果
  2. lookupuidltime,用于记录用户口袋的检查时间
  3. 我需要知道lookup的结果,即结果表应该有uidltimecandy列,告诉我在用户的口袋(假设用户在给予新糖果时会吃旧糖果。)

    每次查询前都有几次交付。 我只需要最新的一个。

    ,例如,

    select l.uid, l.ltime, 
           d.candy  /* ... for max(d.dtime):
              IOW, I want to sort (d.dtime, d.candy) 
              by the first field in decreasing order, 
              then take the second field in the first element */
    from delivery d
    join lookup l 
    on d.uid = l.uid
    and d.dtime <= l.ltime
    group by l.uid, l.ltime
    

    那么,我怎么知道查找找到了什么?

2 个答案:

答案 0 :(得分:1)

我建议outer apply

select l.*, d.candy
from lookup l outer apply
     (select top 1 d.*
      from delivery d
      where d.uid = l.uid and d.dtime <= l.ltime
      order by d.dtime desc
     ) d;

这回答了你的问题。但是,自上次查找以来,用户不会所有糖果吗?或者,我们是否假设当用户获得另一个用户时,用户会吃掉糖果?也许口袋里只有一个糖果。

答案 1 :(得分:1)

使用Top with with Ties获取最新的交付并加入Backup Table

Select * from lookup
    Inner Join (
        Select Top 1  with Ties uid,dtime
          From delivery 
          Order by row_number() over (partition by uid order by dtime desc)) as Delivery
          on lookup.uid = Delivery.uid  and lookup.ltime >= delivery.dtime