Skip to content
Advertisement

sql track changed values

I’m trying to find out what values user changes the most. I have a user table like this:

enter image description here

This is a User Table where entries not get changed. If a user changes something, it creates a new record to track what users change.

Now I want to get something like this:

enter image description here

I want the column names (E-Mail, Phone etc.) as values so I can sort.

Has anyone an idea how I could do that please?

Edit: I’m using SSMS and T-SQL

Advertisement

Answer

It looks horrible but it works:

select * into #q1 from (SELECT Row_number()OVER(ORDER BY i.CreationDate) rn, i.Email, i.Phone, i.Address, i.Phone, i.NumberOfKids
         FROM   user i) as t

SELECT Sum(CASE WHEN a.Email= b.Email THEN 0 ELSE 1 END) as Amount, 'Email' as ColumnName
FROM   #q1 a
       JOIN #q1 b
         ON a.UserID= b.UserID
UNION ALL
SELECT Sum(CASE WHEN a.Address= b.Address THEN 0 ELSE 1 END) as Amount, 'Address' as ColumnName
FROM   #q1 a
       JOIN #q1 b
         ON a.UserID= b.UserID
UNION ALL
SELECT Sum(CASE WHEN a.Phone= b.Phone THEN 0 ELSE 1 END) as Amount, 'Phone' as ColumnName
FROM   #q1 a
       JOIN #q1 b
         ON a.UserID= b.UserID
UNION ALL
SELECT Sum(CASE WHEN a.NumberOfKids= b.NumberOfKids THEN 0 ELSE 1 END) as Amount, 'NumberOfKids' as ColumnName
FROM   #q1 a
       JOIN #q1 b
         ON a.UserID= b.UserID
order by Amount desc
drop table #q1
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement