SQL 2005. The Unit table contains vehicle entries like cars & trucks. The downtime table has the matching entries for the units being out of service for each unit. I'm trying to get the total count of ALL downtime entires for the unit (BB.CntDate) and the most recent downtime entry (AA.MaxDate) in a given date range. I just used '20070101' as an example.
Two questions.
1. Is there a better way to write this Select statement?
2. What if I now want the values from the matching 'Max' record? Not quite sure how to approach this one.
Auguy
Sylvania/Toledo Ohio
Two questions.
1. Is there a better way to write this Select statement?
2. What if I now want the values from the matching 'Max' record? Not quite sure how to approach this one.
Code:
SELECT U.UnitPK, U.UnitNo, U.UnitYear, AA.MaxDate, BB.CntDate
FROM Unit as U
Left OUTER JOIN (SELECT Unitfk, MAX(DateDown) as MaxDate
FROM DownTime
WHERE UnitFk = 1050 and DateDown < '20070101'
GROUP BY Unitfk) as AA on U.UnitPK = AA.Unitfk
Left OUTER JOIN (SELECT Unitfk, COUNT(DateDown) as CntDate
FROM DownTime
WHERE UnitFk = 1050
GROUP BY Unitfk) as BB on U.UnitPK = BB.Unitfk
WHERE U.UnitPK = 1050
GROUP BY U.UnitPK, U.UnitNo, U.UnitYear, AA.MaxDate, BB.CntDate
ORDER BY U.UnitPK, U.UnitNo
Auguy
Sylvania/Toledo Ohio