我有两个表,产品表和抄表由序列号组成,我想显示产品表中的所有机器,并在抄表中显示最近的抄表和日期,以及最近的日期和十二个月前的抄表。
我有这样的查询,但是没有获得12个月前的正确日期和抄表。
select a.Model,a.SerialNumber,a.UnitNumber,a.RecentMeterRead,a.RecentMeterReadDate,b.MeterRead12MonthAgo,b.MeterRead12MonthAgoDate,(a.RecentMeterRead-b.MeterRead12MonthAgo)/12 AS HourByMonth
from
(select s1.ITEMCODE AS Model,s1.SERIALNUMBER as SerialNumber,s1.UNITNUMBER as UnitNumber,
max(s9.METERREAD) as RecentMeterRead,max(s9.METERREADDATE)as RecentMeterReadDate
FROM wk001.serf01 s1
left join wk001.serf09 s9
on s1.SERIALNUMBER=s9.SERIALNUMBER
where s1.BILLTOCUSTOMERCODE='02366'
group by s1.SERIALNUMBER
order by s9.METERREADDATE desc ) as a
left outer join
(select s1.SERIALNUMBER,
s9.METERREAD as MeterRead12MonthAgo,s9.METERREADDATE as MeterRead12MonthAgoDate
FROM wk001.serf01 s1
left join wk001.serf09 s9
on s1.SERIALNUMBER=s9.SERIALNUMBER
where s1.BILLTOCUSTOMERCODE='02366'
group by s1.SERIALNUMBER
having s9.METERREADDATE<=date_sub(max(s9.METERREADDATE),interval 12 month)
order by s9.METERREADDATE desc) as b
on a.SERIALNUMBER=b.SERIALNUMBER
group by a.SERIALNUMBER
order by a.RecentMeterReadDate desc,b.MeterRead12MonthAgoDate DESC;