I’m trying to find out what values user changes the most. I have a user table like this:
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:
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