I have created this query below as a view, to give me the row number for each property and show me all the appointments.I want to be able to find the row that is second to last, with the latest appointment the highest number, so if last rownumber is 3 then I want to show row 2SELECT *FROM (SELECT ROW_NUMBER() OVER (PARTITION BY PropID ORDER BY LatestApptDate) AS PARowNumber, PrevApptID, RowNumber, PropID, UPRN, LatestAppt, LatestApptDate, ImportDateFROM dbo.PreviousASVAppts) dtOrg
Using the view above I create another query to run my report, but it returns with no rows at all, how can I get around this?SELECT PR.PropID, PR.UPRN, PR.Address, PR.Postcode, PR.LatestCP12Date, PA.LatestApptDate AS PrevApptDate, PR.ApptDate AS LatestAppt, PR.NA1, PR.NA2, COALESCE (AA.Appt5, AA.Appt4, AA.Appt3, AA.Appt2, AA.Appt1) AS LatestAppt, AA.ASVStatus, PR.ContractualDueDate, PR.ContractualMonthDue, PR.ContractualWeekDue, PR.TimeContractualDueIn, CASE WHEN AA.ASVStatus = 'Complete' AND DATEDIFF(DAY, PR.ContractualDueDate, PR.CompletedDate) < 60 THEN 'WITHIN' ELSE PR.ContractualCompliance END AS ContractualCompliance,PR.LegalDueDate, PR.LegalMonthDue, PR.LegalWeekDue, PR.TimeLegallyDueIn, CASE WHEN AA.ASVStatus = 'Complete' AND DATEDIFF(DAY, PR.LegalDueDate, PR.CompletedDate) < 60 THEN 'WITHIN' ELSE PR.LegalCompliance END AS LegalCompliance,PR.OutOfCompliance,CASE WHEN AA.ASVStatus = 'Pending' THEN 'Help' WHEN AA.ASVStatus = 'No Access' THEN 'OK' WHEN AA.ASVStatus = 'Complete' AND PR.ApptDate <> PR.LatestCP12Date THEN 'Help' ELSE 'LookAt'END AS ProcessMapFROM dbo.PlymouthASVReport PR INNER JOIN dbo.vwASVActivity AA ON PR.UPRN = AA.UPRN INNER JOIN dbo.vwPreviousASVAppts PAON PR.PropID = PA.PropIDGROUP BY PR.PropID, PR.UPRN, PR.Address, PR.Postcode, PR.ApptDate, PR.LatestCP12Date, PR.NA1, PR.NA2, PR.ContractualDueDate, PR.ContractualMonthDue, PR.ContractualWeekDue, PR.TimeContractualDueIn, PR.ContractualCompliance, PR.LegalDueDate, PR.LegalMonthDue, PR.LegalWeekDue, PR.TimeLegallyDueIn, PR.LegalCompliance, PR.OutOfCompliance, AA.ASVStatus, AA.ASVSubStatus, AA.FirstTimeFix, PA.LatestApptDate, AA.RowNumber, COALESCE (AA.Appt5Date, AA.Appt4Date, AA.Appt3Date, AA.Appt2Date, AA.Appt1Date), COALESCE (AA.Appt5, AA.Appt4, AA.Appt3, AA.Appt2, AA.Appt1), PR.RowNumber, PR.CompletedDate, PARowNumberHAVING PR.RowNumber = 1AND AA.RowNumber = 1AND PA.PARowNumber = MAX(PA.PARowNumber)-1AND PA.LatestApptDate <= COALESCE (AA.Appt5Date, AA.Appt4Date, AA.Appt3Date, AA.Appt2Date, AA.Appt1Date)