I have the following query: for each FacilityCode I am getting LastCompletedOn and LastEDAOn.
SELECT Code ,
MAX(DATEADD(HOUR, Seed_TimeZone.DifferenceFromUTC, CompletedOn)) 'LastCompletedOn' ,
MAX(DATEADD(HOUR, Seed_TimeZone.DifferenceFromUTC,LastUpdateDemographicsDate)) 'LastEDAOn'
FROM PatientCharts WITH ( NOLOCK )
INNER JOIN Facilities WITH ( NOLOCK ) ON Facilities.FacilityId = PatientCharts.FacilityId
INNER JOIN Seed_TimeZone WITH ( NOLOCK ) ON Seed_TimeZone.TimeZoneId = Facilities.TimeZoneId
WHERE Facilities.IsActive = 1
AND PatientCharts.IsDeleted = 0
AND PatientCharts.IsErroneous = 0
--AND dbo.PatientCharts.ChartStatusID=1
GROUP BY Code
I want to put the commented condition “AND dbo.PatientCharts.ChartStatusID=1 ” on LastCompletedOn. I have tried putting the whole query as a subquery but the same value is repeated for each facilitycode. How to accomplish this.
ANSWER
Response suggested by srgerg works fine. However we can get the same result by using a extra join
SELECT Code ,
MAX(DATEADD(HOUR, DifferenceFromUTC, compOn.CompletedOn)) 'LastCompletedOn' ,
MAX(DATEADD(HOUR, DifferenceFromUTC,Prim.LastUpdateDemographicsDate)) 'LastEDAOn'
FROM PatientCharts AS Prim WITH ( NOLOCK )
INNER JOIN Facilities WITH ( NOLOCK ) ON Facilities.FacilityId = Prim.FacilityId
INNER JOIN Seed_TimeZone LEO WITH ( NOLOCK ) ON LEO.TimeZoneId =
Facilities.TimeZoneId
LEFT OUTER JOIN PatientCharts compOn ON compOn.PatientChartId = prim.PatientChartId AND compOn.ChartStatusID=1
WHERE Facilities.IsActive = 1
AND Prim.IsDeleted = 0
AND Prim.IsErroneous = 0
GROUP BY Code
You could try something like this: