我有两张桌子:
delivery
包含uid
,dtime
,candy
列,用于记录哪些用户何时获赠糖果lookup
列uid
和ltime
,用于记录用户口袋的检查时间我需要知道lookup
的结果,即结果表应该有uid
,ltime
,candy
列,告诉我在用户的口袋(假设用户在给予新糖果时会吃旧糖果。)
每次查询前都有几次交付。 我只需要最新的一个。
,例如,
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
那么,我怎么知道查找找到了什么?
答案 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