请帮我弄清楚以下逻辑。当B.DateTime与E.DateTime匹配时,获得E.Location。当B.DateTime<> E.DateTime,然后从之前/之前的E.DateTime获得E.Location。请在('城市A','城市B','城市C','城市E','城市F'城市G'城市X'城市Y')。我将感激你。这是sqlfiddle:http://sqlfiddle.com/#!6/8eb014/1
Base table as B
Id DateTime
201 2015-05-03 08:01
301 2015-05-03 08:20
401 2015-05-03 08:40
Extract Table as E
Id DateTime Location
201 2015-05-03 07:50 City A
201 2015-05-03 08:01 City B
201 2015-05-03 08:50 City C
301 2015-05-03 07:15 City E
301 2015-05-03 08:01 City F
301 2015-05-03 08:20 City G
401 2015-05-03 07:15 City X
401 2015-05-03 08:55 City Y
Desired Result:
Location Id DateTime
City B 201 2015-05-03 08:01
City G 301 2015-05-03 08:20
City X 401 2015-05-03 07:15
我在sqlfiddle上尝试了以下代码,但执行起来有问题:
select B.id, coalesce(E.Location,F.Location),coalesce(E.DateTime,F.DateTime)
from Base B
inner join Extract E
on B.id = E.id
and B.DateTime = E.DateTime
and E.Location in ('City A','City B','City C','City E','City F','City G','City X','City Y')
left join Extract F
on B.id = F.id
and F.DateTime < B.DateTime
and F.Location in ('City A','City B','City C','City E','City F','City G','City X','City Y')
当我使用我的实际数据运行此逻辑时,我得到以下结果。
Location Id DateTime
City B 201 2015-05-03 08:01
City G 301 2015-05-03 08:20
Id 401错过了。
答案 0 :(得分:0)
试试这个。它将通过首先匹配日期然后按日期排序:
select B.id, ca.dt, ca.location
from B
cross apply(select top 1 location, dt
from E
where B.id = E.id
order by case when B.dt = E.dt then 1 else 0 end desc,
E.dt)ca
答案 1 :(得分:0)
请尝试以下查询。您正在使用B和E上的内部联接,它会在日期时间字段中过滤掉401,因为e没有它。
select distinct b.id,coalesce(e.location,a.location) ,coalesce(e.datetime,a.dt)
from base b
left outer join extract e
on b.id = e.id
and b.datetime = e.datetime
and E.Location in ('City A','City B','City C','City E','City F','City G','City X','City Y')
inner join
(
select b2.id,f.location,max(f.datetime) as dt from base b2 join extract f on b2.id = f.id and b2.datetime <> f.datetime
where f.datetime < b2.datetime
group by b2.id,f.location
) a
on b.id = a.id