-- Migration: 032_CreateLastDataUpdatesView
-- Source: OLD/Database/Views/LastDataUpdates.sql
-- Pivot view showing last successful update timestamps by table and type

CREATE OR ALTER VIEW [dbo].[LastDataUpdates]
AS
WITH UPDATE_CTE AS
(
    SELECT du.TableName,
           du.UpdateType,
           du.StartDT,
           ROW_NUMBER() OVER (PARTITION BY du.TableName, du.UpdateType ORDER BY du.StartDT DESC) AS RN
    FROM dbo.DataUpdate du
    WHERE du.WasSuccessful = 1
)
SELECT TableName,
       COALESCE([3], '1970-01-01') AS MassUpdateDT,
       COALESCE(COALESCE([2], [3]), '1970-01-01') AS DailyUpdateDT,
       COALESCE(COALESCE(COALESCE([1], [2]), [3]), '1970-01-01') AS HourlyUpdateDT
FROM
(
    SELECT UPDATE_CTE.TableName,
           UPDATE_CTE.UpdateType,
           UPDATE_CTE.StartDT,
           UPDATE_CTE.RN
    FROM UPDATE_CTE
    WHERE RN = 1
) AS Source
PIVOT
(
    MAX(StartDT)
    FOR UpdateType IN ([1], [2], [3])
) AS PivotTable;
GO
