我有记录所有日期的汽车分期付款Onhire
汽车租赁表,当它返回Offhire
。我一直要求提供的下一个或跟随在成绩表租赁公司的名字,但我不知道该怎么做。此次聘用表的结构如下:
---------------
| Hire |
---------------
| Id |
| CarId |
| Onhire |
| Offhire |
| HireCompany |
|-------------|
如果我对这个表运行一个基本的选择我看到下面的数据。我添加了一个WHERE
拉回来一个特定的汽车就是仍然在租赁和对出租的后续后不久(我用英国的日期格式)。
Id | CarId | Onhire | Offhire | HireCompany
-------------------------------------------------------
10 | 272 | 2019-01-01 | 2019-03-01 | Company A
11 | 272 | 2019-03-02 | 2019-04-01 | Company B
-------------------------------------------------------
正如你所看到的,目前汽车上出租,直到2019年1月3日,但在此之后,它会在出租给Company B
在2019年2月3日。我需要我的查询显示,该车是租赁的时刻,但在一列名为ForwardHire
(或其他)显示,有它在聘请NeXT的公司,以及为表明在未来租赁开始日的列。
所以,我的查询将产生以下期望的结果:
Id | CarId | Onhire | Offhire | ForwardHire | ForwardHireDate
---------------------------------------------------------------------------
10 | 272 | 2019-01-01 | 2019-03-01 | Company B | 2019-03-02
注:我已经知道如何从我的工价表使用外返回一个结果申请,建议我在不同的线程了。
我希望我的问题是有道理的,并且有人可以提供帮助。在SQL查询而言,这是第一个对我来说任何建议和指导表示赞赏。
自加入租用表具有未来onhire
日期行:
select
h1.*,
h2.hirecompany ForwardHire
h2.onhire ForwardHireDate
from hire h1 left join hire h2
on
(h2.carid = h1.carid)
and
(h2.onhire = (select min(onhire) from hire where carid = h1.carid and onhire > h1.offhire) )
where
h1.carid = 272
and
curdate() between h1.onhire and h1.offhire
您是否在寻找lead功能? :
SELECT h.*
FROM (SELECT h.*,
LEAD(HireCompany) OVER (PARTITION BY CarID ORDER BY Id) AS ForwardHire,
LEAD(Onhire) OVER (PARTITION BY CarID ORDER BY Id) AS ForwardHireDate
FROM Hire h
) h
WHERE ForwardHire IS NOT NULL AND ForwardHireDate IS NOT NULL;
使用OUTER APPLY:
SELECT
H.*,
T.ForwardHire,
T.ForwardHireDate
FROM
Hire AS H
OUTER APPLY (
SELECT TOP 1 -- Just the next record
ForwardHire = F.HireCompany,
ForwardHireDate = F.OnHire
FROM
Hire AS F
WHERE
H.CarId = F.CarId AND -- With the same car
F.OnHire > H.OffHire -- With later OnHire
ORDER BY
F.OnHire ASC -- Sorted by OnHire (closeste one first)
) AS T
你只是想lead()
?
select h.*,
lead(h.hirecompany) over (partition by h.carid order by h.onhire) as next_hirecompany
from hire h;
注意:这将返回下一个公司,即使有差距。如果你想在“相邻的”下一步公司,那么我建议一个left join
:
select h.*, hnext.hirecompany as next_hirecompany
from hire h left join
hire hnext
on hnext.carid = h.carid and
hnext.onhire = dateadd(day, 1, h.offhire);