Hello,I am trying to write a query to calculate the running difference between data on different dates. Below is what my table of data looks like. Basically I want to calculate the difference between the total_completed for each state and date.Date States Total_Completed08/27/15 CA 19,952 09/11/15 CA 26,336 10/02/15 CA 35,444 10/08/15 CA 38,278 08/27/15 CO 279709/11/15 CO 326410/02/15 CO 427010/08/15 CO 4297below is what I am trying to achieve:Date States Total_Completed Completed_Difference08/27/15 CA 19,952 0 09/11/15 CA 26,336 6,384 10/02/15 CA 35,444 9,108 10/08/15 CA 38,278 2,834 08/27/15 CO 2797 0 09/11/15 CO 3264 467 10/02/15 CO 4270 1,006 10/08/15 CO 4297 27 below is my code (I almost have what I need) I just can't figure out how show 0 as the completed_difference for the first Date for each state since there is no prior date to calculate against.[code="sql"]MRR_TOTALS_WEEK_OVER_WEEK AS(SELECT T1.[Date],T1.States,T2.Total_Completed,ROW_NUMBER() OVER(PARTITION BY T1.States ORDER BY T1.States,T1.[Date]) AS ORDERING FROM TOTAL_CHARTS T1LEFT JOIN TOTAL_COMPLETED T2 ON T1.[Date] = T2.[Date] AND T1.States = T2.States)SELECT T1.[Date],T1.States,T1.Total_Completed,(COALESCE(T2.Total_Completed,0) - COALESCE(T1.Total_Completed,0)) AS Completed_DifferenceFROM MRR_TOTALS_WEEK_OVER_WEEK T1LEFT JOIN MRR_TOTALS_WEEK_OVER_WEEK T2 ON (T1.ORDERING = T2.ORDERING - 1) AND T1.States = T2.States[/code]
↧