我有一个数据库(更快),可存储数千辆车辆和设备的详细信息。我的目标是获得一份在过去两年中累计行驶不到1000英里的车辆和设备清单(自20090101起)。我正在处理的三个主要表格是:
eheader (has equip info, primary key=ehuid) wheader (has work order info; whehuid links to ehuid, work order primary key is whuid), wmreading (has the meter reading info linked to each workorder; wmwhuid links to whuid).
棘手的部分是,对于每件设备,我需要考虑最近的抄表和大约2年前发生的抄表。
另一个棘手的部分是近似。在2009年1月和2011年1月,我不能保证每辆车都有抄表。我只能假设在3个月左右的时间内在那件设备上发生了工作订单(甚至可能留下一些车辆。)
我需要一个查询,即每辆车将在2009年初的某个范围内从工作订单中读取抄表,并从2010年末至今的某个工作订单中减去相同车辆的抄表。
有关如何查询的想法吗?
答案 0 :(得分:1)
这应该可以帮到你
select
*,
DATEDIFF(D, readingdate, secondreadingdate) as DaysBetweenReadings,
secondmeter-meter as DistanceTravelled
from
(
select
e.*,
r1.readingdate,
r2.readingdate secondreadingdate,
r1.meter,
r2.meter as secondmeter,
rn= ROW_NUMBER() over (
partition by e.ehuid
order by -- prefer the one closer to date
datediff(d, p.dt, r1.readingdate)
, -- from the first reading, prefer the r2 record that is closest to exactly 2 years after
abs(datediff(d, dateadd(year,2,r1.readingdate), r2.readingdate)))
from eheader e
inner join wheader w on w.whehuid = e.ehuid
inner join wmreading r1 on r1.wmwhuid = w.whuid
inner join wmreading r2 on r2.wmwhuid = w.whuid
cross join (select dt=convert(datetime,'20090101')) p -- pivotdate
where -- about 3 months from date
r1.readingdate between p.dt and DATEADD(MONTH, 3, p.dt)
and -- 3 months to or from 2 years after date
r2.readingdate between DATEADD(month, 21, p.dt) and DATEADD(month, 27, p.dt)
) SubQuery
where rn=1
and secondmeter-meter < 1000 -- less than 1000 accrued
order by ehuid