Search code examples
sqlt-sqlaggregatesql-server-2014rollup

TSQL query history table field change count


I need to find an efficient query to count the number of field changes per history table entry.

Each time any data value changes in the Customer Table, a copy of the record is entered into the history table.

I would like a way to count the numbers of changes per entry into the history table. Each field would compare the current entry with the previous entry to determine a difference.

Is there a good way to do this? Without a sproc?

enter image description here


Solution

  • You may start something as the following. I don't have SQL Server environment at this moment, can not verify if everything is correct.

        WITH cte AS (
          SELECT *, rn =  ROW_NUMBER() OVER (PARTITION BY CustomerID ORDER BY ID)
          FROM CustomerHistory
        )
        SELECT 
           c1.*,
           FieldChangeCount = 
              (CASE WHEN c1.ServiceLevel <> c2.ServiceLevel THEN 1 ELSE 0 END) 
                +
              (CASE WHEN c1.Status <> c2.Status THEN 1 ELSE 0 END)      
         FROM cte c1
         LEFT JOIN cte c2
              ON c1.CustomerID = c2. CustomerID
               AND c2.rn = c1.rn - 1 
        ORDER BY c1.LogID