我有一张表,按时间段跟踪客户位置的历史记录。它看起来像这样:
CusID Location Period
1 SYD 201501
1 MEL 201504
1 SYD 201506
我有一个Period
表,其中包含所有句点的列表。有没有办法从这两个表中选择数据,所以我看到了这个结果:
CusID Location Period
1 SYD 201501
1 SYD 201502
1 SYD 201503
1 MEL 201504
1 MEL 201504
1 SYD 201506
答案 0 :(得分:0)
如果只有SQL Server支持ignore nulls
上的lag()
选项:
select cl.cusid, p.period,
lag(cl.location ignore nulls) over (partition by cusid order by period)
from period p cross join
customerlocation cl
on cl.period = p.period;
但是,它没有。一种方法使用`outer apply:
select c.cusid, p.period, cl.location
from period p cross join
(select distinct cusid from customerlocation) c outer apply
(select top 1 cl.*
from customerlocation cl
where cl.period <= p.period and cl.cusid = c.cusid
order by cl.period desc
) cl;
如果您有一个客户表,那么您可以使用它而不是第二个子查询(对于c
)。