2011-02-15 100 views
0

我有一個數據庫(Faster),可以存儲數千輛車輛和設備的詳細信息。我的目標是獲得在過去兩年(自20090101以來)已累積不到1000英里的車輛和設備清單。我處理三個主要的表是:基於滿足範圍條件進行計算

 
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

照顧在ERD表的截圖編輯您的問題嗎? (顯示關係?) – 2011-02-15 22:32:55

回答

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